text:
Q: Routes in angular & php/mysql I have a code with AngularJS that should receive data in a form in a partial and then return a table with the corresponding results in a database mysql any idea how to fix it
First partial form:
    <form>

                <input id="seacrh" autofocus type="text" class="validate" ng-model="searching.name" required>
                Search

                <button class="waves-effect waves-yel btn btnSearch col s12" ng-click="searchingElement()"></button>

        </form>

Second partial table:

                {{element.name}}
                5
                <button class="waves-effect waves-light btn blue">Details</button>

Is that the php code works because the probe by console, but here is:
    <?php
      $data = json_decode(file_get_contents("php://input"));
      $name = $data->name;
      $conn = new mysqli("localhost", "user", "pass","DBName");
      $sql = "SELECT `elements`.name FROM `elements` WHERE `elements`.name='$name'";
      $result = $conn->query($sql);
      $array = array();

      while($row = $result->fetch_assoc()) {
       $array[] = array(
       'name' => $row['name']
      );}
      echo json_encode($array);
  ?>

app.js here is routes and the controller that I am using:
    var app = angular.module('haku_app',['ngRoute'])

    app.config(function($routeProvider){
      $routeProvider
      .when('/',{
        templateUrl: "partials/home.html",
        controller: 'srchCtrl'
      })
      .when('/results',{
        templateUrl: "partials/results.html",
        controller: 'srchCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
    });

    app.controller('srchCtrl',function($scope, $http){
      $scope.serchingElemento= function(){
        $http.post("php/search.php",{'name':$scope.searching.name}).success(function(data){
          $scope.tiendas= data;
          location.href += 'results';
        }).error(function(response){
          console.log(response);
        });
      }
    });

A: I think there's two things going on. The first is, since you're using ngRoute, you should use $location.path() to change views. So in your case: $location.path() = '/results'; instead of location.href = 'results';. Check out the examples in the documentation: https://docs.angularjs.org/api/ngRoute/service/$route.
BEFORE you do that, you need to save the values of the result of the post call to a service. Services in Angular are singletons, meaning you can save data between views, whether or not you're using the same controller. There are numerous examples of how to write an Angular service, so I won't repeat it. Here's a great example: AngularJS - Passing data between pages.
So your logic would go:

*

*Make post call

*In callback, save post data to your service

*Change views using $location.path()

*In the new view, fetch the data from the service into the controller, and render in the view.

If you really want to do multiple views and nested views, check out ui-router: https://github.com/angular-ui/ui-router. It's more complicated than ngRoute. I don't think you need it, however. But if you work on a more complicated application you may find it helpful.
Finally, I noticed your controller says $route.tiendas = data, but your view says element in elements. Make sure you're using the right variable names.
Hope this helps.


text:
Q: Ubuntu 20.04 Network issues OS: Ubuntu 20.04
Each time that I start the pc and log into my account the ethernet Connection doesn't work and the ethernet icon does not appear in the top-bar.

cat /etc/netplan/*.yaml output:

# Let NetworkManager manage all devices on this system
network:
  version: 2
  renderer: NetworkManager

if I run sudo lshw -C network i get the following output

  *-network DISABLED
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: enp3s0
       version: 0c
       serial: e0:3f:49:46:0b:53
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical
       configuration: broadcast=yes driver=r8169 latency=0 link=no multicast=yes
       resources: irq:18 ioport:d000(size=256) memory:f7100000-f7100fff memory:f2100000-f2103fff

I saw that i had to put it's logical name inside the /etc/network/interfaces
auto enp3s0
iface enp3s0 inet dhcp

toggle the managed field inside /etc/NetworkManager/NetworkManager.conf
[ifupdown]
managed=true

and reboot.
I did so but didn't work.
The only way that is currenty working is to run sudo dhclient but i have to run it at each reboot. What can i try for a perma solution?

A: I had to follow the steps given in  this answer
Basically run these two commands
sudo touch /etc/NetworkManager/conf.d/10-globally-managed-devices.conf
sudo systemctl restart NetworkManager

A: Edit /etc/network/interfaces and post there ONLY
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

The network device will be controlled by Network Manager, and you'll have the settings back.
When you add entries to this files, it disables Network Manager.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: how convert this time string? i would convert this time (strftime?)
2013-07-12T07:59:27+0000

in a more simple  to read "12/07/2013" (dd-mm-aaaa) and with +2 (i'm in Italy, so this time must be 09:59, no importance for seconds).
Thank you very much!
PS Could you tell me what "kinda of time expression" is, so next time i'll be more capable to search in Google without ask? :)

A: Try this:
echo date('d/m/Y H:i', strtotime('2013-07-12T07:59:27+0000'));

For more, read this: http://php.net/manual/en/function.strtotime.php


text:
Q: How to Get the currently logged on user name I am building a small intranet app in which I need to display the user name of the person who opens the webpage.
I tries with:
WindowsIdentity.GetCurrent().Name.ToString();

But this always displays my user name on the webpage.

A: Please see THIS - basicaly you need to enable Integrated windows authentication and the use one of the following:
System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string strName = p.Identity.Name;

or
string strName = HttpContext.Current.User.Identity.Name.ToString();

or
string strName = Request.ServerVariables["AUTH_USER"]; //Finding with name
string strName = Request.ServerVariables[5]; //Finding with index

All 3 cases should retrun a string containing DomainName\WinNTLoggedUserName.

A: You can use this:
Page.User.Identity.Name

P.S: Don't forget to check entities whether they were null first.

A: use this code
if (User.Identity.IsAuthenticated)
 Label1.Text = User.Identity.Name;
else
 Label1.Text = "No user identity available.";

look at the following article Forms Authentication in ASP.NET

A: See http://forums.asp.net/t/1102996.aspx/1. I think the reason that you see your own name is that the web app is running under your credentials.
So use HttpContext.Current.User.Identity.Name instead and make sure that you have enabled Forms authentication in web.config


text:
Q: AVRoutePickerView doesn't pick up change to route made by overrideOutputAudioPort(.speaker) I start a VoIP call using CallKit, use AVAudioSession.sharedInstance.overrideOutputAudioPort(.speaker) to force the audio to speaker, and then open an AVRoutePickerView.
The selected output in the view is iPhone-- the ear speaker on the iPhone. I would expect it to show instead that speaker is selected.
What could be causing this? Should I be forcing the output to the speaker in a different way? Is there a different way I can expose the route choosing functionality?
What's strange is that if you lock the phone and look at the CallKit UI, it shows that it is routing to speaker

A: I encountered the same problem. In my code, I overrode the audio route to .none and it worked indeed. But the AvRoutePickerView showed .speaker selected. It confuse me.


text:
Q: nginx add headers when returning 400 codes I'm developing an ember.js app with a laravel backend. I'm trying to return http error codes with php if something goes awry. I've noticed that when issue a PUT request and return a 400 status code, my CORS headers get ignored by my conf file which breaks my ember frontend. I have no idea why the PUT/400 code combo makes nginx ignore my conf. Any help would be much appreciated.
 server {
  listen                *:80 ;

  server_name           userchamp.com;
  access_log            /var/log/nginx/embertest.com.access.log;

  location / {

    root  /var/www/embertest/public;
    try_files  $uri  $uri/  /index.php?$args ;
    index  index.html index.htm index.php;

  }

  location ~ \.php$ {

        if ($request_method = 'OPTIONS') {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;

        return 204;
     }

     if ($request_method = 'POST') {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

     }

     if ($request_method = 'PUT') {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

     }

     if ($request_method = 'DELETE') {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

     }
    root  /var/www/embertest/public;
    try_files  $uri  $uri/  /index.php?$args ;
    index  index.html index.htm index.php;
    fastcgi_index index.php;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param  PATH_TRANSLATED $document_root$fastcgi_path_info;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param    APP_ENV dev;
    fastcgi_param     APP_DBG true;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include fastcgi_params;
  }
}

A: For nginx >= 1.7.5
Append "always" to the header definition:
add_header 'Access-Control-Allow-Origin' '*' always;

For nginx < 1.7.5
According to the nginx official document of ngx_header_module, the add_header can't work when response code is 400
syntax:     add_header name value;
default:    —
context:    http, server, location, if in location

Adds the specified field to a response header provided that the response code equals
200, 201, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables.

In another way,  you can try the HttpHeadersMoreModule, which is more powerful.


text:
Q: Inner join "not unique table" I'm trying to create a procedure using inner joins. I keep getting following error:
Not unique table/alias: 'car'

What am i doing wrong?
My procedure
DELIMITER //
CREATE PROCEDURE orderCreate(IN _LicenseNumber varchar(30), _Phonenumber varchar(20))
BEGIN
INSERT INTO `order` (carID, clientID)
Select car.id, client.id
FROM car, client, owns
INNER JOIN car
ON car.id = owns.carID

INNER JOIN owns
ON owns.clientID = client.id;

WHERE  car.licensenumber = _LicenseNumber
AND client.phonenumber = _Phonenumber
SELECT LAST_INSERT_ID();

END //
DELIMITER ;

A: You are doing both an INNER JOIN and a cartesian product (which is the same in MySQL1):
FROM car, client, owns
INNER JOIN car
ON car.id = owns.carID

INNER JOIN owns
ON owns.clientID = client.id;

Just remove car and owns from your FROM statement.
If you want both, you have to add an alias to car and owns:
FROM car AS car1, clients, owns AS owns1

References

*

*http://dev.mysql.com/doc/refman/4.1/en/join.html

INNER JOIN and , (comma) are semantically equivalent in the absence of
  a join condition: both produce a Cartesian product between the
  specified tables

A: I think you have to many tables:
Try:
INSERT INTO `order` (carID, clientID)
Select car.id, client.id
FROM car
INNER JOIN owns
ON owns.clientID = client.id;
WHERE  car.licensenumber = _LicenseNumber
AND client.phonenumber = _Phonenumber
SELECT LAST_INSERT_ID();


text:
Q: Access sessions for action link in Nested Tabset and Tabpanels in R shiny Here I'm trying to create a actionlink between tabs, but I have many nested tabs within and since I'm calling the links from the nested tabs itself and not the main session, I'm not able to place the id's correctly.
I've looked into this question : Question , but this works for only the main session.
Here's a part of my reproducible code:
     ui <- fluidPage(
 navbarPage(id = "Navbar",
 tabPanel("About",..
 actionLink("link_to_overview", "Let's start with the Overview!"), <--- This works
 ),

 tabPanel("Overview",
          tabsetPanel(id = "Tab_ov",
          tabPanel("Flights",..
          actionLink("link_to_airlines", "Let's go to the Airlines!"),<--- This doesn't work

          ),

          tabPanel("Airlines",..
          actionLink("link_to_domestic_stats", "Let's go to the Domestic!") <--- This doesn't work
          ),
          )),

    tabPanel("Statistics",
          tabsetPanel(id = "stats_tab",
          tabPanel("Domestic",..
          ),

          tabPanel("International",..),
          ))
          ))

server <-     function(input, output, session) {
observeEvent(input$link_to_overview, {
    newvalue <- "Overview"
    updateTabItems(session, "Navbar", newvalue)
  })

observeEvent(input$link_to_airlines, {
    updateTabsetPanel(session, inputId = 'Flights', selected = 'Tab_ov')
    updateTabsetPanel(session, inputId = 'Overview', selected = 'Airlines')
  })

observeEvent(input$link_to_domestic_stats, {
    updateTabsetPanel(session, inputId = 'Overview', selected = 'Statistics')
    updateTabsetPanel(session, inputId = 'stats_tab', selected = 'Domestic')
  })

  }

A: Try this:
library(shiny)
library(tidyverse)
ui <- fluidPage(navbarPage(
    id = "Navbar",
    tabPanel(
        "About",
        actionLink("link_to_overview", "Let's start with the Overview!")
    ),

    tabPanel("Overview",
             tabsetPanel(
                 tabPanel(
                     "Flights",
                     value = 'flights',
                     actionLink("link_to_airlines", "Let's go to the Airlines!")

                 ),

                 tabPanel(
                     "Airlines",
                     value = 'airlines',
                     actionLink("link_to_domestic_stats", "Let's go to the Domestic!")
                 ), id = "Tab_ov"
             ),value = 'ovview'),

    tabPanel(
        "Statistics",
        tabsetPanel(
                    tabPanel("Domestic", value = 'domestic'),

                    tabPanel("International", ''),
                    id = "stats_tab")
    )
))

server <-     function(input, output, session) {
    observeEvent(input$link_to_overview, {

        updateTabsetPanel(session, "Navbar", 'ovview')
    })

    observeEvent(input$link_to_airlines, {
        updateTabsetPanel(session, inputId = 'Tab_ov', selected = 'airlines')
    })

    observeEvent(input$link_to_domestic_stats, {
        updateTabsetPanel(session, inputId = 'Navbar', selected = 'Statistics')
        updateTabsetPanel(session, inputId = 'stats_tab', selected = 'domestic')
    })

}

shinyApp(ui, server)


text:
Q: What about downvoting SQL answer not using ANSI (inner) joins In old releases inner joins where coded like this
Select * from table_a, table_b
where table_a.some_column = table_b.some_column
and ... (further conditions)

Using ansi standard joins you can rewrite this as
Select *
from table_a
  inner join table_b on table_a.some_column = table_b.some_column
where ... (further conditions)

The advantage is, that the reader is told which columns are used for the join and has not to solve the puzzle which conditions describe the join and which describe the where condition.
What about downvoting all answers using old style inner joins until they are rewritten in ANSI style ?
Not intended as punishment, but as community pressure to enforce the improved coding style?
Edit:
Can you give me hints, which of the following items caused the downvoting of my question

*

*wanting to enforce some kind of sql syntax in the answers of SO

*the proposal to use downvotes to achieve this

A: Unfortunately, especially if the old syntax still worked, all that you'd do is attract more up-votes to the answer.
Why?
Well, people would see the down-vote on what to them looks like a perfectly valid answer and they'd be more likely to up-vote to counter your down-vote. Which would have the opposite effect to that which you intended.
Far better to provide your own answer, as Bill suggests, and perhaps comment on the original answer pointing out the new information.

A: Actually, you're the one that's wrong here.
Both types of join follow the ANSI standard.  The comma-separated syntax with conditions in the predicate is ANSI-89.  The INNER JOIN syntax is ANSI-92.  They are both "ANSI joins".
This bizarre but widespread belief that the ANSI-89 syntax is some sort of proprietary, obsolete or deprecated syntax seems to be the result of endless repetition by uninformed or misinformed people on the internet who refer to the ANSI-92 syntax as just "ANSI joins" and the ANSI-89 syntax as "old style" or something similar.  It's simply not correct.
Portability concerns aside, an answer using the ANSI-89 syntax is still a correct answer.  It's a minor semantic issue, such as using a subquery vs. a CTE.  Of course in certain versions of certain DBMSes the ANSI-89 syntax may be deprecated or not supported, and if the question specifies such an environment then a comment or downvote would be warranted - but otherwise, stop being anal.
The only answers that anybody should be downvoting are those indicating (either explicitly or implicitly) that the ANSI-89 standard is not actually ANSI compliant.

A: I'd be against downvoting the first code example you gave if it worked.  It's still helpful.  It's better to just provide your own answer with the new style join syntax and let the community (and OP) decide which they prefer with upvotes.


text:
Q: Strings over 15 characters get turned to ε■ε■ε■ε■ε■ε■ε■ε■ε I have been implementing a factory for a component based game engine recently. I am deserializing objects by reading in from a file what component they need and what to initialize them with. It works except for when I try to read in a property longer than 15 characters. At 15 characters, it reads it in perfectly, anything longer and I get "ε■ε■ε■ε■ε■ε■ε■ε■ε" as output.
I am using std::string to store these lines of text.
Example:
JunkComponent2 test "1234567890123456" test2 "123456789012345"
With this the value of test becomes garbage, while test2 stays perfectly intact.
Any idea's what might be going on?
char line[1024];

while (file.getline(line, 1024))
{
    std::vector<std::string> words;
    std::string word;
    int j = 0;
    for (unsigned i = 0; line[i] != '\0' && i < 1024; ++i)
    {

        if (line[i] == ' ' && j > 0 && line[i - 1] != '\\')
        {
            words.push_back(word);
            j = 0;
            word = "";
        }
        else
        {
            ++j;
            word += line[i];
        }
    }
    words.push_back(word);

    // std::cout << (*Parts)["JunkComponent"]->GetName() << std::endl;

    Component* c = (*Parts)[words[0]]->clone(words);
    object->AddComponent(words[0], c);
    for (std::list<Member*>::iterator it = members.begin(); it != members.end(); ++it)
    {
        for (unsigned i = 0; i < words.size(); ++i)
        {
            if ((*it)->GetName() == words[i])
            {
                if (words[i + 1][0] == '\"')
                {
                    std::vector<char> chars;
                    chars.push_back('\"');
                    chars.push_back('\\');
                    for (unsigned int n = 0; n < chars.size(); ++n)\
                    {
                        words[i + 1].erase(std::remove(words[i + 1].begin(), words[i + 1].end(), chars[n]), words[i + 1].end());
                    }
                    Container((*it)->GetMeta(), GET_MEMBER(data.GetData(), (*it)->GetOffset()), (*it)->GetName()).SetValue<std::string>(words[i + 1]);
                }
                else
                {
                    Container((*it)->GetMeta(), GET_MEMBER(data.GetData(), (*it)->GetOffset()), (*it)->GetName()).SetValue<int>(std::stoi(words[i + i]));
                }
                ++i;
                break;
            }
        }
    }
}

GET_MEMBER Macro expands to:
#define GET_MEMBER(P, OFFSET) ((void *)(((char *)(P)) + (OFFSET)))

SetValue Function: (data is a void*)
template <typename T>
void SetValue(T data_)
{
    memcpy(data, &data_, sizeof(T));
}

A: I'll take a stab having just eyed your code. GET_MEMBER is really nasty and I think that's where your problem is. It seems to rely on std::string being convertible to char*, which it is not. Why does your code work with strings shorter than 15? Well that's more than likely because std::string on most popular implementations actually contains a special case for strings where it keeps an internal buffer of length 16 ( last element \0 ) to avoid dynamic memory allocation. When the string is larger than 15 this buffer is uninitialized because it isn't used. The correct way to access the string is by using operator[].


text:
Q: How to make PyGal display x labels on top of bars? How to make PyGal display labels (not values) on top of the horizontal bars, rather than on the other side of the axis?
I can't find any relevant pygal.Config, pygal.style.Style argument, nor figure out the necessary CSS.
Currently stuck trying CSS, but while I target the right elements and change the anchor, the text is still behind the bars (doesn't react to z-index as it's SVG), and overlaps the axis and should be shifted to the right (but doesn't react to setting margin, padding).
{{ id }}.axis.y text {
  text-anchor: start;
  z-index: 99999999999 !important;
}


text:
Q: Right justify a list of values I am an irregular AHK user and typically work at the edge of my knowledge.
I usually need to keep the help files to hand.
I am using Version 1.0.48.05 and have a problem.
In a nutshell - I want to print a list of numeric values using the Gui interface so that the values line up under each other justified to the right.
I can not find an easy or robust way of doing that.  What am I missing.
The values can vary from 0 to 9999.  They are always integers.
====================
This is a snippet of code before I try to right-justify :
tabpos := 200
Gui, Add, Text, x%tabpos% y300, %value1%
Gui, Add, Text, x%tabpos% y320, %value2%
Gui, Add, Text, x%tabpos% y340, %value3%
Gui, Add, Text, x%tabpos% y360, %value4%

That prints my values at the "tabpos" position but all left-justified.
My first attempt to right-justify was to use a function which padded with a number of spaces determined by the length of the "value" .  For exammple :
Gui, Add, Text, x%tabpos% y300, % pad(6, value1)

pad(width, val)
{
   ans :=  SubStr("      ", 1, width-StrLen(val)).val
   return ans
}

But that did not work well as the width of a digit was not the same as (or a multiple of) the width of a space.
Where I introduced a multiple into the function, that worked differently for different type sizes and typefaces.
My second attempt was to adjust the "tabpos" by a number of pixels depending on the length of the "value".  For example :
newpos := tabpos - 9*StrLen(value1)     ; Where a digit is 9 pixels wide
Gui, Add, Text, x%newpos% y300, %value1%

But that only works well where a digit is exactly 9 pixels wide.  I would like a more general, robust method.
I have tried using the AHK SetFormat instruction, but have failed to get any effect.  Perhaps I am using it incorrectly.  In any event, it appears that SetFormat works by padding with spaces and so it would have the same effect as my first attempt (above) with the same problems.
==================
Any suggestions will be very welcome.
I would like the method to work whatever the typeface, type size, whether bold or normal, and whatever the DPI of the monitor.

A: How about...
Gui, Add, Text, x100 y100 w100 Right, 123
Gui, Add, Text, x100 y120 w100 Right, 123456
Gui, Add, Text, x100 y140 w100 Right, 123456789


text:
Q: is_proplist in erlang? How can get the type of a list. I want to execute the code if the list is proplist.
Let us say L = [a,1,b,2,c,3, ...]. Is the list L, I'm converting it to proplist like
L = [{a,1}, {b,2}, {c,3}, ...].

How can I determine whether the list is a proplist? erlang:is_list/1 is not useful for me.

A: You'd need to check whether every element of the list is a tuple of two elements.  That can be done with lists:all/2:
is_proplist(List) ->
    is_list(List) andalso
        lists:all(fun({_, _}) -> true;
                     (_)      -> false
                  end,
                  List).

This depends on which definition of "proplist" you use, of course.  The above is what is usually meant by "proplist", but the documentation for the proplists module says:

Property lists are ordinary lists containing entries in the form of either tuples, whose first elements are keys used for lookup and insertion, or atoms, which work as shorthand for tuples {Atom, true}.

A: You can use something like:
is_proplist([]) -> true;
is_proplist([{K,_}|L]) when is_atom(K) -> is_proplist(L);
is_proplist(_) -> false.

but necessary to consider that this function cannot be used in guards.


text:
Q: Long Term Storage of a Notebook HardDrive and RAM I had an old laptop which failed; I've removed the hard drive and RAM and disposed of the laptop (it was kind of old, anyway).
While I realize the RAM may only be "useful" for a period of time, the hard drive should always maintain some usefulness... (The specifications of the equipment shouldn't matter for my question)
What is the proper way to store such items for the long[er] term? Just a static free bag for each item or something more? Could they be stored together? Is the static-free back necessary even? What are the chance's the equipment will become damaged without one?

A: I would use the anti-static bag and include a small packet of desiccant to keep moisture off any connectors and so on.
One possible issue with a hard drive is sticktion where the drive motor fails to spin the platter(s) after sitting for some time.  Not sure how common this is.  IBM training used to mention this as an issue when using spare drives in servers that were not running as "hot" spares.
Also keep a device like an external USB case handy as interfaces can change.  Your PATA/IDE drive won't work too well if the system you have available in the future is all SATA

A: Yes, a static-free bag is preferred. This is quite stochastic through: I kept my drives (old 20Gb ones) for years just stacked in a box and they worked fine after, but you can never determine if a drive will work after someone eventually discharges at it.
They can be stored together, but only if you sure that no mechanical damage will be done by ones to others; a RAM module will probably be crashed if a hard drive is dropped on it with a sharp angle even from 5cm height.
Also it's a good idea to keep all parts on something soft (foam rubber maybe) to protect them from excessive stresses when moving their storage, and place a small bag of silicagel to keep moisture off.


text:
Q: Character Replacement: Break-Lines I have a few areas in an application of mine that I have <textarea> tags so users can enter messages to one another.  A problem with some messages had been plaguing me for a while, but I could never figure out what the problem was.  I would open up all the messages at once and save them in hidden  tags.  When the user 'opened' the message, the data from the  tag would be gathered and shown in a lightbox for the user.  For some reason, it wouldn't open some of those messages.
One of my users noticed that if you used a line-break (using 'shift+enter') in the message, it would break the Javascript when it tried to retrieve the message.  Since this is only a problem when trying to read the message, I should be able to replace it when the message is sent in the first place.
How can I detect a line-break and replace it when it is submitted?
str_replace(???,"/n",$string)

A: As you've discovered, javascript can't handle a line break mid-string.  In other words, the following output will cause a js error...

You could add a backslash at the end of the broken line to fix this error...

As user765476 said, you could use PHP's nl2br function on the text.  But to add, it is usually best to do so only while you're actually building the html output.  One reason being is if you ever allow users to edit text they've already submitted, they will see
's everywhere in the textbox and you'll have to devise yet another script to replace those
's.
If you truly want to forbid users from submitting line breaks (and any possible carriage returns) at all though, then use something like this basic PHP code to replace them with a single space...
str_replace(array("\r\n", "\r", "\n"), ' ', $message);

Note: order of search strings is important.  First pass replaces all "\r\n"'s, second pass replaces any remaining "\r"'s, third pass replaces any remaining "\n"'s  (Edit: I forgot "\r" is recognized in IE javascript, just not in certain other browsers).

A: Maybe this function
is what you're looking for? It converts newlines to
 tags.


text:
Q: Would Xamarin help in porting win32 DLL to android shared library? I am working on a project in which I need to include NGSpice simulation library in an Android application and of course be able to use it.
I need to port the NGSpice windows DLL to my android application, how far would xamarin help me in this task? its a win32 dll, its not .Net based dll, please have a look at NGSpice link
Thanks.

A: Yes that is possible using the Android NDK.
Since reading through all the docs can be somewhat overwhelming at first, I'll give you a quick tour.

*

*Install the NDK

*Create a folder named jni inside your project directory

*Inside that folder create a subfolder lib and copy the required source files of your library to that folder

*Inside the jni folder create two files, wrapper.c and wrapper.h. These files should contain high level wrappers around your native library suitable for binding from the C# side using DllImport

*Inside the jni folder create a file named Android.mk

*Inside the jni folder create a file named Application.mk

*run ndk-build

*Once ndk-build completes successfully create subfolder lib inside your C# project directory and copy the generated native libraries including their surrounding folder to lib. Your folder structure should look like this: <project> -> libs -> armeabi and x86 (both folders contain an architure specific .so file). By establishing this folder structure, we ensure that MonoDroid will automatically load the matching library for the current runtime architecture.

*Create new C# Class file Foo.cs inside your C# project. This class implements the binding glue between your native library wrapper and the C# world.

*Profit!

Android.mk:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := libFoo
LOCAL_SRC_FILES := wrapper.c lib/source1.c lib/sourcen.c

include $(BUILD_SHARED_LIBRARY)

Note: lib/source1.c and lib/sourcen.c need to be substituted by the names of your actually library source files.
Application.mk:
APP_ABI := armeabi armeabi-v7a x86

This line tells ndk-build which architectures you wish to support. x86 is for the Intel Android HAXM Simulator.
wrapper.h:
#pragma once

typedef struct _InternalState
{
    FILE *m_pFile;
} InternalState;

//////////////////////
// Public API

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

InternalState *FooCreate(int foo);
void FooDoStuff(InternalState *pState);

#ifdef __cplusplus
}
#endif /* __cplusplus */

wrapper.c:
//////////////////////
// Public API

InternalState *FooCreate(int foo)
{
  // Initialize actual library here
  // return state if necessary
}

void FooDoStuff(InternalState *pState)
{
  // Call actual library here
}

Foo.cs:
public class Foo :
  IDisposable
{
  private IntPtr handle;
  private bool disposed;

  private Foo(IntPtr handle)
  {
    this.handle = handle;
  }

  ~Foo()
  {
    Dispose(false);
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  public void Dispose(bool disposing)
  {
    disposed = true;

    Close();
  }

  #region Native Imports

  [DllImport("libFoo")]
  private static extern IntPtr FooCreate(int seed);
  [DllImport("libFoo")]
  private static extern void FooDoStuff(IntPtr pHandle);

  #endregion

  private void VerifyHandle()
  {
    if (handle == IntPtr.Zero)
      throw new InvalidOperationException("Handle not initialized");
  }

  #region Public API

  public static Foo FromSeed(int seed)
  {
    IntPtr handle = FooCreate(seed);
    if(handle == IntPtr.Zero)
      throw new System.Exception("Failed to create native object");

    return new Foo(handle);
  }

  public void DoStuff()
  {
    VerifyHandle();

    FooDoStuff(handle);
  }

  #endregion
}


text:
Q: O que é exatamente complexidade de tempo? Estava lendo a respeito de buffer circular e sua implementação e me deparei com o termo complexidade de tempo ( no caso, o texto afirma que o buffer circular tem complexidade O (1) ). Pelo que li a respeito, essa é uma métrica que se aplica ao tempo que um algoritmo leva para executar uma tarefa. Seria isso ? Essa métrica se aplica para o código como um todo ou serve também para arrays e outras estruturas de dados? Como medir a complexidade ?

A: É isso mesmo, é grosso modo o tempo que o algoritmo leva para resolver o problema.
Quase sempre, quando se discute complexidade de algoritmos, ou citamos vulgarmente que um algoritmo é tratável ou intratável, está a se falar do tempo.
Também existe a complexidade da memória ou armazenamento, ou seja, espaço ocupado pelo algoritmo em RAM ou disco enquanto o trabalho não estiver terminado.
Em certos casos a complexidade de memória ou armazenamento é importante pois pode existir um trade-off (escolha de Sofia) entre complexidade de tempo e complexidade de memória.
Por exemplo, em algoritmos de sort, QuickSort e Merge Sort têm complexidade típica no tempo idêntica. Porém, Merge Sort é O(n) na complexidade de memória, enquanto QuickSort não precisa de memória extra além da própria massa de dados a ser ordenada. Por outro lado, QuickSort pode ter a complexidade de tempo degradada em alguns casos, enquanto Merge Sort mantém a complexidade de tempo sempre baixa. Então é preciso escolher o que for menos prejudicial para o caso de uso.
Como estimar a complexidade, é assunto para um livro. Mas um exemplo simples para introduzir a questão, em pseudocódigo:
def faz_algo(n):
   for i in range(0, n):
      for j in range(0, n):
         ... faz alguma coisa aqui ...

A função acima tem complexidade quadrática no tempo, proporcionalmente a "n", pois tem dois ciclos aninhados, ambos executam "n" vezes. A complexidade de memória é aparentemente O(1) (constante), mas uma conclusão só seria possível sabendo o que "alguma coisa" significa...


text:
Q: basic mysql sha1 password valid check I am using sha1 function to store my password in mysql DB..
$passwordHash = sha1($password);

From google I got this
From user registration
sha1( sha1(users_plaintext_password)+random string )

To check
server computes sha1( users_hashed_password_in_database +
$_SESSION['random_string'] )

if $_POST['password'] ==
sha1( users_hashed_password_in_database + $_SESSION['random_string'] )

My question is how do I check for validation?Is this the correct method?? And does using some random string as salt give my password more protection??

A: I would do it as follows:
$seed = 'some random string';
$passwordHash = sha1($password.$seed);

Then do the same with data entered by the user:
$pass = $_POST['password'];
if(sha1($pass.$seed) == $passwordHash){
    //log user in
}

The seed is a good idea, because users often pick passwords that are easy to guess. Another advantage is that you may be able to restore security to your site by changing the seed if someone manages to hack their way in.


text:
Q: jQuery YouTube Array from Playlist Scope Issue I'm trying to pull a list of YouTube videos based on a playlist ID, which is then passed to a YouTube carousel script. I'm having some issues with scope though that I'm not sure how to resolve it.
Basically, I declare the array yt_videos, then populated it with the IDs of the individual videos in the $.each loop. When I try to access this array in the outer function, it's undefined. I'm sure the solution is fairly simple, just can't get there on my own.
Here's the Fiddle: http://jsfiddle.net/wardrobe/Nz87f/2/
Here's the JS:
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/PLDD79FC8870945AA5?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
var yt_videos = [];

$.getJSON(playListURL, function(data) {
    var list_data="";
    $.each(data.feed.entry, function(i, item) {
        var feedTitle = item.title.$t;
        var feedURL = item.link[1].href;
        var fragments = feedURL.split("/");
        var videoID = fragments[fragments.length - 2];
        yt_videos.push(videoID);
    });
});

/*Video height and width*/
var yt_height = 346;
var yt_width = 615;

/*-----DO NOT EDIT BELOW THIS-----*/
jQuery(document).ready(function () {
    var yt_html = "";

    for (var num=0, len=yt_videos.length; num<len; ++num){
        yt_html = yt_html + "

";
    }

    jQuery('#yt_container').html('

<object width="'+ yt_width +'" height="'+ yt_height +'"><param name="movie" value="http://www.youtube.com/v/'+ yt_videos[0] +'?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+ yt_videos[0] +'?version=3&hl=en_US" type="application/x-shockwave-flash" width="'+ yt_width +'" height="'+ yt_height +'" allowscriptaccess="always" allowfullscreen="true" wmode="transparent"></embed></object>

'+yt_html+'
');
    var embeded_cssObj = {
        'width' : yt_width,
        'height' : yt_height
    }
    jQuery('#yt_embededvideo').css(embeded_cssObj);
    jQuery('#yt_videosurround').css(embeded_cssObj);
    jQuery('#mycarousel').jcarousel({
        wrap: 'circular'
    });
});

function change_embeded(video_id){
    jQuery('#yt_embededvideo').html('<object width="'+ yt_width +'" height="'+ yt_height +'"><param name="movie" value="http://www.youtube.com/v/'+ video_id +'?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+ video_id +'?version=3&hl=en_US" type="application/x-shockwave-flash" width="'+ yt_width +'" height="'+ yt_height +'" allowscriptaccess="always" allowfullscreen="true" wmode="transparent"></embed></object>');
}

A: Accessing data that might not have yet arrived from the server.
Some reorganising - try this - http://jsfiddle.net/QQ34V/
jQuery(document).ready(function () {

var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/PLDD79FC8870945AA5?v=2&alt=json&callback=?',
videoURL= 'http://www.youtube.com/watch?v=',
yt_videos = [],
yt_height = 346,
yt_width = 615,
yt_html = "";

    $.getJSON(playListURL, function(data) {
        var list_data="";
        $.each(data.feed.entry, function(i, item) {
            var feedTitle = item.title.$t;
            var feedURL = item.link[1].href;
            var fragments = feedURL.split("/");
            var videoID = fragments[fragments.length - 2];
            yt_videos.push(videoID);
        });

        for (var num=0, len=yt_videos.length; num<len; ++num){
            yt_html = yt_html + "

";
        }

        jQuery('#yt_container').html('

<object width="'+ yt_width +'" height="'+ yt_height +'"><param name="movie" value="http://www.youtube.com/v/'+ yt_videos[0] +'?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+ yt_videos[0] +'?version=3&hl=en_US" type="application/x-shockwave-flash" width="'+ yt_width +'" height="'+ yt_height +'" allowscriptaccess="always" allowfullscreen="true" wmode="transparent"></embed></object>

'+yt_html+'
');
        var embeded_cssObj = {
            'width' : yt_width,
            'height' : yt_height
        }
        jQuery('#yt_embededvideo').css(embeded_cssObj);
        jQuery('#yt_videosurround').css(embeded_cssObj);
        jQuery('#mycarousel').jcarousel({
            wrap: 'circular'
        });

        /* for correct placement of this function you will need to provide more info on where/ how it is called */
        function change_embeded(video_id){
            jQuery('#yt_embededvideo').html('<object width="'+ yt_width +'" height="'+ yt_height +'"><param name="movie" value="http://www.youtube.com/v/'+ video_id +'?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+ video_id +'?version=3&hl=en_US" type="application/x-shockwave-flash" width="'+ yt_width +'" height="'+ yt_height +'" allowscriptaccess="always" allowfullscreen="true" wmode="transparent"></embed></object>');
        }

    });

});

*I have not fully checked this code, but note here that the access to your variables are now within the .ajax() callback function, making sure that they available when you 'get' the data back.


text:
Q: Perl Invalid conversion in printf I have an error code:
Invalid conversion in printf: "%A"' printing %A characters in a URL

Here is my code:
$url =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
printf "%-10s $url\n", $res_request{$key};

How can I fix this?
Thank you very much,
AL

A: Instead of putting $url in the format string, use an %s format:
printf "%-10s %s\n", $res_request{$key}, $url;

(You should never interpolate variables into the format string that have parts that may be mistaken for formatting codes.)


text:
Q: How to convert String to Integer array and back in JAVA I want to deserialize String into int[] array and back. I try something like this
public static int[] getIntArrayFromString(String string, int stringMaxLenght) {
    byte[] bytes = string.getBytes();

    int rest = bytes.length % 4;
    int times = (bytes.length - rest) / 4;

    int[] result = new int[stringMaxLenght];
    int maxIndex = 0;
    for (int i = 0; i < times; i++) {
        if (times > stringMaxLenght)
            break;
        int in = createIntFromBytes(bytes[i * 4 + 0], bytes[i * 4 + 1], bytes[i * 4 + 2],
                bytes[i * 4 + 3]);
        result[i] = in;
        maxIndex = i;
    }
    byte[] restb = new byte[4];
    for (int i = 0; i < rest; i++) {
        restb[i] = bytes[(maxIndex + 1 * 4) + i];
    }

    if (times < stringMaxLenght) {
        int lastInt = createIntFromBytes(restb);
        result[maxIndex + 1] = lastInt;
    }
    return result;
}

public static int createIntFromBytes(byte byte0, byte byte1, byte byte2, byte byte3) {
    byte[] byteArray = new byte[4];
    byteArray[0] = byte0;
    byteArray[1] = byte1;
    byteArray[2] = byte2;
    byteArray[3] = byte3;
    return createIntFromBytes(byteArray);
}

public static String getStringFromIntegerArray(int[] intArray) {
    ByteBuffer buffer = ByteBuffer.allocate(intArray.length * 4);
    for (int integer : intArray) {
        byte[] bs = createBytesFromInt(integer);
        buffer.put(bs);
    }
    return getStringFromBytes(buffer.array());
}

public static int createIntFromBytes(byte[] bytes) {
    return ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).getInt();
}

public static String getStringFromBytes(byte[] bytes) {
    String string = new String(bytes);
    return string.trim();// otherwise it creates string with empty chars
}

but is seems not working for example string "Signature". Do you have any idea, what I am doing wrong, or how it should be done more nicely.

A: public static void main(String[] args) {
    int[] test = {1,2,3,4,5,6,7,8};

    // From int[] to String
    String input = Arrays.toString(test);

    // Test
    System.out.println(input);

    // String back to int[]
    test = toIntArray(input);

    // Test
    input = Arrays.toString(test);
    System.out.println(input);

}

public static int[] toIntArray(String input) {
    String beforeSplit = input.replaceAll("\\[|\\]|\\s", "");
    String[] split = beforeSplit.split("\\,");
    int[] result = new int[split.length];
    for (int i = 0; i < split.length; i++) {
        result[i] = Integer.parseInt(split[i]);
    }
    return result;
}

Result:
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

A: How to convert String to Integer array and back in JAVA

Though the content of your question is not clear to me, assuming that you want to know if a built-in function available, to convert the int array to string you can make use of Arrays.toString function, for example:
  String strArr = Arrays.toString(new int[]{112, 12 ,13});
  System.out.println(strArr);

It will create following type of output format:
  [112, 12, 13]

A: The problem was in this row. There was a bad index offset.
wrong: restb[i] = bytes[(maxIndex + 1 * 4) + i];
good: restb[i] = bytes[(maxIndex * 4) + i + 4];
So it maybe helps somebody. This code is now working well.
public static int[] getIntArrayFromString(String string, int stringMaxLenght) {
byte[] bytes = string.getBytes();

int rest = bytes.length % 4;
int times = (bytes.length - rest) / 4;

int[] result = new int[stringMaxLenght];
int maxIndex = 0;
for (int i = 0; i < times; i++) {
    if (times > stringMaxLenght)
        break;
    int in = createIntFromBytes(bytes[i * 4 + 0], bytes[i * 4 + 1], bytes[i * 4 + 2],
            bytes[i * 4 + 3]);
    result[i] = in;
    maxIndex = i;
}
byte[] restb = new byte[4];
for (int i = 0; i < rest; i++) {
    restb[i] = bytes[(maxIndex * 4) + i + 4];
}

if (times < stringMaxLenght) {
    int lastInt = createIntFromBytes(restb);
    result[maxIndex + 1] = lastInt;
}
return result;
 }

public static int createIntFromBytes(byte byte0, byte byte1, byte byte2, byte byte3) {
    byte[] byteArray = new byte[4];
    byteArray[0] = byte0;
    byteArray[1] = byte1;
    byteArray[2] = byte2;
    byteArray[3] = byte3;
    return createIntFromBytes(byteArray);
}

public static String getStringFromIntegerArray(int[] intArray) {
    ByteBuffer buffer = ByteBuffer.allocate(intArray.length * 4);
    for (int integer : intArray) {
        byte[] bs = createBytesFromInt(integer);
        buffer.put(bs);
    }
    return getStringFromBytes(buffer.array());
}

public static int createIntFromBytes(byte[] bytes) {
    return ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).getInt();
}

public static String getStringFromBytes(byte[] bytes) {
    String string = new String(bytes);
    return string.trim();// otherwise it creates string with empty chars
}


text:
Q: Handlebars helper inheritance? Is it possible for a Handlebars helper to inherit from another Handlebars helper? for example:
Handlebars.registerHelper('DateHelper', function(date, format) {
    if (!date) return;
    var formatted = format;
    return new Handlebars.SafeString('<time>' + formatted + '</time>');
});

Handlebars.registerHelper('shortDate', function(date) {
    // I want to something like this..
    return Handlebars.helper.DateHelper(date, moment(value).format('D MMM YYYY'));
});

A: As far as I am aware it is not directly possible to inherit from one Handlebars helper to another, however it is possible with an ordinary constructor function, for example:
var DateHelper = function HandlebarsDateHelper(date, format) {
    return new Handlebars.SafeString('<time>' + format + '</time>');
};

Handlebars.registerHelper('shortDate', function(date) {
    if (!date) return;
    return new HandlebarsDateHelper(date, moment(value).format('D MMM YYYY'));
});


text:
Q: Node-gyp issue with, cannot find module I installed node-gyp as a global module npm install node-gyp -g
When I run node-gyp, the bellow issue occurred
current node version 'v15.0.1'
Os Ubuntu 20.04.3 LTS
Looking for some help.
node-gyp
node:internal/modules/cjs/loader:903
  throw err;
  ^

Error: Cannot find module 'nopt'

Require stack:
 /usr/share/nodejs/node-gyp/lib/node-gyp.js
 /usr/share/nodejs/node-gyp/bin/node-gyp.js

    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:900:15)
    at Function.Module._load (node:internal/modules/cjs/loader:745:27)
    at Module.require (node:internal/modules/cjs/loader:972:19)
    at require (node:internal/modules/cjs/helpers:88:18)
    at Object.<anonymous> (/usr/share/nodejs/node-gyp/lib/node-gyp.js:4:14)
    at Module._compile (node:internal/modules/cjs/loader:1083:30)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1112:10)
    at Module.load (node:internal/modules/cjs/loader:948:32)
    at Function.Module._load (node:internal/modules/cjs/loader:789:14)
    at Module.require (node:internal/modules/cjs/loader:972:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/share/nodejs/node-gyp/lib/node-gyp.js',
    '/usr/share/nodejs/node-gyp/bin/node-gyp.js'
  ]
}


text:
Q: 100% height for div inside another div with margins I have a div inside a div. The CSS/HTML is below. I am trying to figure out how to make the inner div have true height: 100%; with no overflow and what not. No matter what I try the border of the inner div gets cropped because of the outer div's overflow: hidden.
For reasons I cannot modify the content or style of either divs. I can, however, wrap the inner div in other divs if needed. This is not done through JavaScript which is why I cannot modify the outer or inner divs.
Also, this has to work in IE8.
The outer div style won't change much -- only the width, height, background-color, and margin.
The inner div could be anything. It could have a bigger border, it could have no border, it could be who knows what.

#outer
{
 width: 200px;
 height: 200px;
 background-color: yellow;
 margin: 20px;
 overflow: hidden;
 position: absolute;
}

#wrapper
{
  height: 100%;
}

#inner
{
 border: 1px solid red;
 height: 100%;
}

   a

A: You can use css flex property for #wrapper
#wrapper {
    display: flex;
    flex-flow: column;
    height: 100%;
}

#outer
{
 width: 200px;
 height: 200px;
 background-color: yellow;
 margin: 20px;
 overflow: hidden;
 position: absolute;
}

#wrapper /* adding flex */
{
  display: flex;
flex-flow: column;
height: 100%;
}

#inner
{
 border: 1px solid red;
 height: 100%;
}

   a

it will work on all latest browser but this won't work on IE8.

A: jsfiddle
change the #wrapper height to only 99% will solve the problem.
The reason why the inner is getting cut off because:
#inner {
    height: 100%; //this means it equals to 200px
    border: 1px solid red;  //1px at the top border and 1px at the bottom added to the height of the #inner so now it becomes 202px, which will get cut off by overflow:hidden
}


text:
Q: how to get the node_modules folder in an aws lambda function So I am learning how to create alexa skills and I have create two sucessfully following the steps below but for some reason when I follow these steps now I am missing the node_modules folder and the package.json. This is causing the following error when I test my skill:

Unable to import module 'index': Error

The steps I am following are:
- go to the aws console select lambda
- select create new function
- blueprints -> select alexa-skill-kit-sdk-factskill -> configure
- select existing role ->  lambda_basic_execution
- create function

It was my understanding that the alexa-skill-kit-sdk-factskill came with these dependencies. Is there a way to add them in manually if so how? I have tried to find a console but I don't see where that is in the lambda workspace.
Here is a screen shots of the project where it did add the folder and json file

Here is on of my current project

A: I have had this problem, but unfortunately, Lambda console doesn't give us console to install nodejs dependencies.
So, you have to actually deploy your lambda function. There are many ways to do that, but more popular are:

*

*Node Lambda package (for node)

*Create ZIP and deploy it in console (Not recommended because of size limitation)

*AWS CLI
As you're learning the Alexa Skills, I would suggest you the way Amazon suggests devs to create and organise Alexa Skill and Lambda function.
Use ASK CLI
For creating new Alexa Skill.
This will create a directory, which will have:

*

*Skill's intent Schema

*Skill's lambda function

*Plus, you can pass a template to create skill for a specific template. Here is list of templates created by Amazon devs.

*For eg, command for creating Skill code, for a fact-template skill
 ask new [--template [template-name] [--url <url>]]
 [-n|--skill-name <name>]
 [-p| --profile <profile>] [--lambda-name <lambda-name>]

Using ASK CLI, will give you the advantage of deploying your skill and lambda simultaneously.
I know ASK CLI is a lot to take in so quickly, but once you get the hang of it, it is a very useful tool for Alexa developers.

A:
You can zip the whole directory content locally and upload the zip to
  lambda. But yeah you can't edit the code in the console then.

Remember that your handler file name must be mentioned as it is in Handler section.
Like if your file name is app.js then app.handler.


text:
Q: Infinite number of slides appended to an angular-carousel I use rn-carousel with ng-repeat and I am able to swipe between all my items. However there is an infinite number of blank items appended to the list, meaning that I can swipe past my own items to the right an infinite number of time, it displays empty slides.
This happens even with a very basic markup:

and regardless of the device.
Also the next '>' control link is never displayed on any slide, which is quite misleading when the user lands on the first slide and does not even know there are others slides on the right.
Any guess on what could be the source of the problem? Or a way to debug?

A: In case someone faces the same issue, the root cause was my implementation of UseCaseCtrl.getProjects() which used to return an object. Internally, rn-carousel will use .length to determine the number of slides. Since it tried to make .length of an object with nested items, it could not work. The problem was solved by returning an array instead.


text:
Q: IIS website redirect HTTP to HTTPS for a specific domain I have one website on IIS 8. The trick is that I have multiple domains connected to this website. I have certified one of them so far. Because of this, I can't just redirect all HTTP to HTTPS. This is my attempt at doing the redirect to HTTPS for a specific domain. It does not work. Its not common to not do all or nothing for the redirect so there isn't many resources for this online.
Thank you for the help! Example1
Example2


text:
Q: How to bind properties of one ObservableCollection of ListView to properties of SelectedItem of another ListView? So I have a few ListViews. The first is binded to ObservaleCollection<ComPort>. All properties of ComPort may take some predefined values. Other ListViews are responsible for that properties: they show all that possible (predefined) values and SelectedItem should be the current value of that property of ComPort from the first ObservaleCollection.
I can't attach images so here is an external picture, it would make the situation clean: http://i.stack.imgur.com/ZBRRx.png
<Window.Resources>
    <ResourceDictionary x:Name="rd">
        <l:ComPorts x:Key="vComPorts"/>
        <l:SystemPorts x:Key="vSystemPorts"/>
        <l:BaudRates x:Key="vBaudRate"/>
        <l:Parities x:Key="vParities"/>
        <l:DataBits x:Key="vDataBits"/>
        <l:StopBits x:Key="vStopBits"/>
        <l:Timeouts x:Key="vTimeouts"/>
        <l:ComPort x:Key="vSelectedPort"/>
    </ResourceDictionary>
</Window.Resources>

...
<ListView
            Name="PortsList"
            Grid.Row="1"
            Grid.Column="0"
            Margin="5"
            VerticalAlignment="Stretch"
            ItemsSource="{StaticResource vComPorts}"
            DataContext="{StaticResource vComPorts}"
            SelectedValuePath="PortName"
            SelectedValue="{Binding ElementName=SystemPortsList, Path=SelectedItem.Value}"
            SelectionChanged="PortsList_SelectionChanged"
            MouseDoubleClick="PortsList_MouseDoubleClick">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <CheckBox />
                        <TextBlock Margin="5,0,0,0" Text="{Binding Path=Name}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <ListView
            x:Name="SystemPortsList"
            Margin="5"
            VerticalAlignment="Stretch"
            DataContext="{Binding Source={StaticResource vSelectedPort}}"
            ItemsSource="{Binding Source={StaticResource vSystemPortsView}}"
            SelectedItem="{Binding Source={StaticResource vSelectedPort}, Path=PortName}"
            MouseEnter="SystemPortsList_Refresh"
            MouseLeave="SystemPortsList_Refresh"
            Grid.Row="1"
            Grid.Column="1" SelectionChanged="SystemPortsList_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Name="tb" Margin="5,0,0,0" Text="{Binding Path=Name}" />
                    </StackPanel>
            </ListView.ItemTemplate>
        </ListView>

I've tried to make an instance of class ComPort for saving current value of selected item from the first ListView, but anyway I can't cope with it without help. How this task should be solved?

A: 1) Instead of handling SelectionChanged on the PortsList ListView, bind your checkbox to the ListViewItemsPanel like so:
<CheckBox IsChecked={Binding IsSelected, RelativeSource=Parent/>

2) Add an x:Name to your first ListBox, say x:Name="ComPortLB";
3) Remove DataContext on SystemPortsList;
4) Fix SelectedItem on SystemPortsList like so:
SelectedValue="{Binding ElementName=ComPortLB, Path=SelectedValue.PortName}"

I haven't tested any of this code and I haven't done this kind of stuff for a while, so I apologize for errors, but it should get you closer.  I've also had to make some assumptions about your classes since you don't provide enough information.


text:
Q: Get arguments in batch file I am creating a programming language and I'm trying to implement command line arguments for when you run the program. When you open the program file it uses a batch file called start.bat
start.bat:
@echo off
set FILE=%1

cd %~dp0
title AtomScript - %FILE%
java -jar AtomScript.jar %FILE%

Also. I understand that when making an interpreted language, C or C++ is recommended. I'm using java to prototype it.
Okay. So my problem is I want to run the program with arguments like so:
C:/Users/User/Programs>main.atom arg1 arg2 arg3
The program then should print:
arg1
arg2
arg3

My question is, how do I get those arguments from the command line in a batch script?

A: %1 expands to the first command line parameter, %2 ... %9 to 2nd-9th accordingly.
You can also pass the entire command line with %*:
java -jar AtomScript.jar %*

More info.


text:
Q: Timing of action using edge-trigger of clock Let's say I have a code as follows:
always @(clock)
begin
  if (condition is met)
     a <= 0
  else if (another condition is met)
     b <= 0
end

I want a <= 0 at the posedge of the clock and b <= 0 at the negedge of the clock. How do I specify this?
What I'm doing right now is...
always @(clock)
begin
   if (condition is met)
      @(posedge clock) a <= 0
   else if (another condition is met)
      @(negedge clock) b <= 0
end

A: Use two always blocks. One for posedge and another for negedge.
always @(posedge clock) begin
  if (condition is met)
     a <= 0;
end
always @(negedge clock) begin
  if (!(condition is met) && (another condition is met))
     b <= 0;
end


text:
Q: Cannot build an Ionic iOS app using Azure devops I'm having a hard time building my iOS application and generating IPA file through Azure devOps pipeline. On my Mac I'm able to run ionic cordova build ios --release command and automatically sign the app through Xcode but I get lots of errors from the pipeline.
Steps: Install apples certificates and provisioning profile (these are the ones automatically generated by Xcode on my local machine), run build command (ionic cordova build ios --release --developmentTeam="XXXX") and I get the Command failed with exit code 65 error:
Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_IRLScannerViewController", referenced from:
      objc-class-ref in Scan.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

** BUILD FAILED **

I also tried switching from the build command to an Xcode task with autocatically signing but I also get an error: AppName has conflicting provisioning settings. AppName is automatically signed for development, but a conflicting code signing identity iPhone Distribution has been manually specified.
What can I do?

A: Managed to get rid of the Xcode build erros adding a prior CMD job: sed -i '' 's/iPhone Distribution/iPhone Developer/g' platforms/ios/cordova/build-release.xcconfig


text:
Q: async/await not working as expected in jQuery each() My async/await sample code not working properly.
I am using jquery .each loop, along with Async/await functionality but not working as expected
I would expect the output to be:
one
John
July
Anja
two
done

However the actual output is:
one
two
done
John
July
Anja

$(document).ready(function() {
  function one() {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log("one");
        resolve();
      }, 500);
    });
  }

  function two() {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log("two");
        resolve();
      }, 300);
    });
  }

  function namePrint(name) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(name);
        resolve();
      }, 400);
    });
  }
  async function msg() {
    try {
      await one();
      $("#myTable tr").each(async function(index, item) {
        await namePrint($(this).find("#name").text());
      });
      await two();
      console.log("done");
    } catch (e) {
      console.log("Error:", e);
    }
  }
  msg();
});

      Firstname
      Lastname
      Email

      John
      Doe
      john@example.com

      July
      Dooley
      july@example.com

      Anja
      Ravendale
      Anja@example.com

A: Many thanks for the comments.
I had to use for loop to solve the problem, but it would be nice if could use jquery each loop.
var trArray=$("#myTable tr").toArray();
for(tr of trArray) await namePrint(tr.cells["name"].textContent);

A: Change nameprint time to 100.
setTimeout is not an async function.so it won't wait for printing John july anja. So you have to adjust your settimeout function time.Or you can use sleep function using ES6 Promise.
Every setimeout will create stack of functions to run which will run after time gets over.
See if this helps.
 function namePrint(name) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(name);
        resolve();
      }, 100);
    });
  }


text:
Q: curl and wget fail to verify wildcard Let's Encrypt certificate, but browsers work fine We've obtained a wildcard certificate from Let's Encrypt for civility.social and *.civility.social, using certbot. This works fine on all browsers and with curl and wget when verifying https://civility.social, or https://graphql.civility.social. The A records for those (sub)domains point to the same server, from which the certbot challenge was completed.
Later we've added a subdomain hosted on a different server, meet.. To use the same certificate on a different server, we copied the files making up the wildcard certificate from the original server to meet.. Both servers use NGINX. The problem is that wget and curl fail to fetch anything from meet.civility.social, even though browsers don't complain. wget fails even with --no-check-certificate.
$ $ wget -v --debug --no-check-certificate https://meet.civility.social
Setting --check-certificate (checkcertificate) to 0
Setting --check-certificate (checkcertificate) to 0
DEBUG output created by Wget 1.20.3 on linux-gnu.

Reading HSTS entries from ~/.wget-hsts
URI encoding = 'UTF-8'
Converted file name 'index.html' (UTF-8) -> 'index.html' (UTF-8)
--2020-06-26 21:39:15--  https://meet.civility.social/
Resolving meet.civility.social (meet.civility.social)... 157.245.170.94
Caching meet.civility.social => 157.245.170.94
Connecting to meet.civility.social (meet.civility.social)|157.245.170.94|:443... connected.
Created socket 3.
Releasing 0x000055ae59be63e0 (new refcount 1).
Initiating SSL handshake.
SSL handshake failed.
Closed fd 3
Unable to establish SSL connection.

$ curl https://meet.civility.social/
curl: (60) SSL certificate problem: unable to get local issuer certificate

What might be going on here?

A: You need to update ca-certificates package.
On my machine I have no SSL errors:
mvutcovici@DESKTOP-QMNRLV6:~$ curl -v https://graphql.civility.social
*   Trying 167.71.155.126:443...
* TCP_NODELAY set
* Connected to graphql.civility.social (167.71.155.126) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=civility.social
*  start date: Jun  6 08:45:19 2020 GMT
*  expire date: Sep  4 08:45:19 2020 GMT
*  subjectAltName: host "graphql.civility.social" matched cert's "*.civility.social"
*  issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x563dffb227c0)
> GET / HTTP/2
> Host: graphql.civility.social
> user-agent: curl/7.68.0
> accept: */*
>
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 500
< server: nginx/1.17.10 (Ubuntu)
< date: Sat, 27 Jun 2020 05:27:14 GMT
< content-type: application/json; charset=utf-8
< content-length: 153
< access-control-allow-origin: *
< etag: W/"99-9KmtOnsArqM8/UCTY4AvEYVjSiM"
< strict-transport-security: max-age=63072000
<
{"errors":[{"message":"Context creation failed: Incorrect method GET from 199.241.131.83 requesting {}","extensions":{"code":"INTERNAL_SERVER_ERROR"}}]}
* Connection #0 to host graphql.civility.social left intact
mvutcovici@DESKTOP-QMNRLV6:~$

Edit 1:
For meet.civility.social the webserver is not sending the intermediate certificate. You can see this with a network capture in WireShark. You are presenting only the certificate which covers *.civility.social and civility.social, but the intermediate certificate Let's Encrypt Authority X3 is omitted. certbot should take care of installing the proper intermediate certificate, for more details see: https://letsencrypt.org/certificates/
You need to concatenate the server and intermediate certificate:
# civility.social
-----BEGIN CERTIFICATE-----
MIIFaTCCBFGgAwIBAgISA4ROk0Mr6HcT5XbuumfDaJrDMA0GCSqGSIb3DQEBCwUA
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0yMDA2MDYwODQ1MTlaFw0y
MDA5MDQwODQ1MTlaMBoxGDAWBgNVBAMTD2NpdmlsaXR5LnNvY2lhbDCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMLtBpnuOOOwKUo3j7sTASUcidiE3yVA
LN56oK9wIY5uJ9kqJTRjFDbQrAIfaAv3p6b1KNBEfuBQ6TRbWEuRrFDi4WUCaNQS
UKwK4jIqJhH3fxxZejUjM2hewKbnTgvGpWQyQkk9kDzDW7klo1nffUdj1z0nW14h
z1NxmoMWerxVqfrkuJ9o2Fl7zkvhmr26i+p8ehSJctVQtNnSdeQGGe2eX5D4VQSI
dMmfjzfzl0U9002tjLmY5iUknRf6EIJxrgPb2E81Ay47vsL4FS7AWNvsF3jOomQh
RdP4IjUs3NvmUF7x5YRWFWO9aOabLotc2L4FKiVeLRUGMMgXLwmDy98CAwEAAaOC
AncwggJzMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB
BQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUpViiA3AsreWjZkSAaOSW+fal
66YwHwYDVR0jBBgwFoAUqEpqYwR93brm0Tm3pkVl7/Oo7KEwbwYIKwYBBQUHAQEE
YzBhMC4GCCsGAQUFBzABhiJodHRwOi8vb2NzcC5pbnQteDMubGV0c2VuY3J5cHQu
b3JnMC8GCCsGAQUFBzAChiNodHRwOi8vY2VydC5pbnQteDMubGV0c2VuY3J5cHQu
b3JnLzAtBgNVHREEJjAkghEqLmNpdmlsaXR5LnNvY2lhbIIPY2l2aWxpdHkuc29j
aWFsMEwGA1UdIARFMEMwCAYGZ4EMAQIBMDcGCysGAQQBgt8TAQEBMCgwJgYIKwYB
BQUHAgEWGmh0dHA6Ly9jcHMubGV0c2VuY3J5cHQub3JnMIIBBAYKKwYBBAHWeQIE
AgSB9QSB8gDwAHYA5xLysDd+GmL7jskMYYTx6ns3y1YdESZb8+DzS/JBVG4AAAFy
iQU30AAABAMARzBFAiAr8zcVbe0ZZD9/hTkvMUe6YE9WE26xqsjhBGE7F4BZ2QIh
ALUtrBQy/FZxIJ+54tvSyS9V3x5DrHEjLYrVSX+XfW6nAHYAB7dcG+V9aP/xsMYd
IxXHuuZXfFeUt2ruvGE6GmnTohwAAAFyiQU4IQAABAMARzBFAiEA/wXl+iyT1h0g
wJT9s/94+MFMf2Vc7mY/WWnXUEs5IgECIC5fmsw4PSpvYjBd/gXGi8HUO7oPSura
OCBR0QBK2iFzMA0GCSqGSIb3DQEBCwUAA4IBAQCILd6E26gp+6YVzhzAmhDHiWi3
d7gg/ttmtCml99Ud5vhWTJFc7ORJVGO2zp4IO2QxBg8aDVIDjIr/QmgUT7+Fdjyi
FXJ1m1KMJIs3gySY1gfBXMN4wSCVmTMlXds1ukGrwrR86ZshmBhIHe/qOnt+o5nT
Y4DGWpWffEp4eNk5EzVAgnXpLFva4JpDJgmtSwBOzIHQEDieqP5JsApRAgt+WYLv
BQwYQsKya/YLCHTzp5MVOjVWpGo+jHSFQEPaxR8MiFfMNSO3+Ymxc4X1w0kHvxFt
aXqTubdI9BoqEcB7d0qnApY2Bw7hkSOgzsgy4r4dvrasLTW+xjAB7S2iXbfP
-----END CERTIFICATE-----
# Let's Encrypt Authority X3
-----BEGIN CERTIFICATE-----
MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow
SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT
GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF
q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8
SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0
Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA
a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj
/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T
AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG
CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv
bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k
c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw
VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC
ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz
MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu
Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF
AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo
uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/
wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu
X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG
PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6
KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==
-----END CERTIFICATE-----


text:
Q: PostgreSql - Ordering a mix of numeric strings and number ranges What I have is a mix of numbers and ranges in a column like so
Range
---------
1
3-4
4
5-10
8-9
12-20
2
7
9
11-14
6
10

What I want is them to be ordered in the following manner
Range
---------
1
2
3-4
4
5-10
6
7
8-9
9
10
11-14
12-20

Won't work - The simple ORDER BY "Range" produces the following (as expected)
Range
---------
1
10
11-14
12-20
2
3-4
4
5-10
6
7
8-9
9

Is there a "simple" way for me to make it order the values (ranges and numbers) as I want them to?

A: You can use such query:
SELECT *
FROM YourTableName
ORDER BY
    CAST(
        CASE WHEN position('-' in Range) > 0
        THEN substr(range, 0, position('-' in Range))
        ELSE Range
        END
    as integer)

In your ORDER BY statement you first extract a number from your range:

*

*If condition position('-' in Range) > 0 is met, this means that you have a '-' somewhere in your string, so you should take a number until '-', which is achieved using substr(range, 0, position('-' in Range)). E.g. if you have 10-14 in your column, this step only takes 10.

*If the previous condition is not met then you take the Range.

After the above checks are done, you the number. In this case you cast this value to integer, so it correctly orders number (i.e. so 10 comes after 2, etc.)
The above query assumes that you always have the data in the format you specified - either number only or number-number. It would fail for other cases.

A: Given your actual question, this is most easily done using split_part():
order by cast(split_part(range, '-', 1) as int)

This, of course, assumes that the values in the string are numeric.  If they are not, then ask another question, with example values and how they should be sorted.


text:
Q: EXC_BAD_ACCESS while sending data with game center I'm trying to make a multiplayer memory game with game center.
I followed the tutorial in this link, connected two devices to a match, got the match started.
In the game, when one device flip a card, the other must flip that card too.To do this, I have to send an id type value to the other device, so I can flip the card in two devices.
Here is the code;
- (void)gameTouchBegin:(id)target {
    [target flipTheCard];
    [self sendCardMove:target];
}

- (void)sendCardMove:(id)target {
     MessageCard message;
     message.message.messageType = kMessageTypeCard;
     message.target = target;
     NSData* data = [NSData dataWithBytes:&message length:sizeof(MessageCard)];
     [self sendData:data];
}

- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
    if (message->messageType == kMessageTypeCard) {
    NSLog(@"Other player flipped the card.");
    // I can successfully write this line.
    // So I can reach inside this function.
    MessageCard * messageInit = (MessageCard *) [data bytes];
    id gTarget = (id)messageInit->target;
    [gTarget flipTheCard];

    // At the three code lines above, I got an error.

    }
}

As I commented at the end of the code, I got EXC_BAD_ACCESS error and the app crashes.
I know this is a complicated stuff, anyone have an idea?
Thanks in advance.

A: I think that may cause the problem.
I define the message body like this;
typedef struct {
    Message message;
    id target;
} MessageCard;

I suppose xCode doesn't let me define "id" type variables in struct. So I can't send id type to other device. There is no solution about that, I must find another way to find out which card it is.
Thank you.


text:
Q: currvita - vertical distance between bullters How to make smaller vertical distance between item bullets in one section only ?
\documentclass[a4paper,10pt]{article}
\usepackage[TextAligned,NoDate]{currvita}
\usepackage{fullpage}
\begin{document}
\begin{cv}{John Doe}

\begin{cvlist}{Sec1}
\item[2000-01--2012-12] x
\item[2000-01--2012-12] y
\item[2000-01--2012-12] z
\end{cvlist}

%how to change vertical distance between items in on section only, leaving other sections unaffected ?
\begin{cvlist}{Section that needs smaller vertical distance}
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\end{cvlist}

\begin{cvlist}{SecN}
\item[2000-01--2012-12] x
\item[2000-01--2012-12] y
\item[2000-01--2012-12] z
\end{cvlist}

\end{cv}
\end{document}

A: You can do so by putting
\setlength{\itemsep}{%
        -0.50\baselineskip plus 1pt minus 1pt%
      }%

inside the cvlist environment where you want to reduce the spacing
The MWE:
\documentclass[a4paper,10pt]{article}
\usepackage[TextAligned,NoDate]{currvita}
\usepackage{fullpage}
\begin{document}
\begin{cv}{John Doe}

\begin{cvlist}{Sec1}
\item[2000-01--2012-12] x
\item[2000-01--2012-12] y
\item[2000-01--2012-12] z
\end{cvlist}

%change the values in itemsep appropriately
\begin{cvlist}{Section that needs smaller vertical distance}
\setlength{\itemsep}{%
        -0.50\baselineskip plus 1pt minus 1pt%
      }%
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\item[2000-01--2012-12] A
\end{cvlist}

\begin{cvlist}{SecN}
\item[2000-01--2012-12] x
\item[2000-01--2012-12] y
\item[2000-01--2012-12] z
\end{cvlist}

\end{cv}
\end{document}


text:
Q: What does 40bit - 256 encryption actually mean? I've recently been looking at SSL certificates and have seen a number of vendors selling a low end certificate which encrypts at between 40-256 bits.
However, when I visit a site which has such a certificate it reports that site is using a 256bit encrypted connection.
Since we all know 40bit encryption is now woefully inadequate how can they be offering this as possibility?
It seems as if they are offering something which will range from being completely unsuitable to suitable - is that the case?

A: It seems like you mix up two things:
The bit length of the key-pair that belongs to a certificate has nothing to do with the used cipher and it's strength that is used for SSL connections.
The certificate is used for authentication purposes and uses asymmetric cryptography (public and private key forming a key-pair).
The shorter bit lengths you have mentioned are used for encryption of the connection and they are used for symmetric algorithms - their key length is much smaller having an equal security compared to asymmetric crypto algorithms.
Which symmetric algorithm is used for encrypting an SSL connection is negotiated between client and server when the connection starts. Usually the strongest algorithm supported by both sides is used.


text:
Q: How to sort combo box by frequently used? So, simple question, I have combo box in my database and I want items that I have selected most frequently to appear first the next time that I add a record.

A: I would suggest adding a Long Integer field to the table consituting the row source for your combobox, and incrementing the value held by such field either on the AfterUpdate event of the combobox, or following the main operation being performed by your form.
Then, sort the items in the combobox by this new field in descending order.

A: I assume that your combo box selects a lookup value in for a property (PropertyID) that is saved in a table (MainTable).
You can get the number of times this property has been selected with
SELECT PropertyID, COUNT(*) AS SelectedTimes
FROM MainTable
GROUP BY PropertyID

Now get the sorted lookup table by using this query as sub-query:
SELECT L.PropertyID, L.Name
FROM
    LookupTable L
    ( SELECT PropertyID, COUNT(*) AS SelectedTimes
      FROM MainTable
      GROUP BY PropertyID) X
    ON L.PropertyID = X.PropertyID
ORDER BY X.SelectedTimes DESC, L.Name

I'm also sorting by name in case two entries have the same count.

A: As usage may change over time, you should record the time when an item was selected. Then you can weight the usage, so recent usage of an item have higher weight than those items used, say, a year ago.
Then you can run a query to list the usage having the most recently used items at top:
Select Item, Sum(1 / DateDiff("h", [SelectedTime], Now())) As Usage
From ItemUsage
Group By Item
Order By Sum(1 / DateDiff("h", [SelectedTime], Now())) Desc

Of course, this linear weighting may be too simple. You can apply any math to the usage like square or log.


text:
Q: Can't remove columns from a dataframe, output turns into a logical vector There seems to be something wrong with the data.frame I get from the cSplit function.
I can't extract columns without NAs from using the code below:
data_places <- data_table[ , colSums(is.na(data_table)) == 0 ]

The output is a Named logi vector rather than a data.frame that doesn't have columns that possess rows with NAs.
The issue is mainly due to the data.frame output of the cSplit function of of the splitstackshape package. The issue also appears using the data.table package.
I tried creating a new data.frame that extracts the columns of the data.frame output of the cSplit function and the code above works fine.
Any ideas what's wrong with cSplit's data.frame output?
Here's a sample of my code:
library(splitstackshape)
data <- data.frame(V1=c("Place1-Place1-Place1-Place1-Place3-Place5",
          "Place1-Place4-Place2-Place3-Place3-Place5-Place5",
          "Place6-Place6",
          "Place1-Place2-Place3-Place4"))

data_table <- cSplit(data, "V1", sep="-", direction = "wide")
data_places <- data_table[ , colSums(is.na(data_table)) == 0 ]
data_places
str(data_places)

A: We need to use with=FALSE as the output of cSplit is a data.table object.
data_table[ , colSums(is.na(data_table)) == 0 , with=FALSE]
#      V1_1   V1_2
#1: Place1 Place1
#2: Place1 Place4
#3: Place6 Place6
#4: Place1 Place2

If we look at the ?data.table

with -
   By default with=TRUE and j is evaluated within the frame of x;
  column names can be used as variables. When with=FALSE j is a
  character vector of column names or a numeric vector of column
  positions to select, and the value returned is always a data.table.
  with=FALSE is often useful in data.table to select columns
  dynamically.

Another option would be to use Filter
Filter(function(x) all(!is.na(x)), data_table)


text:
Q: iphonesdk appending string issue i have a nsmutablearray which have 5 objects.
for example if it contain objects like apple, cat , ball, dog ,ant, i want them to append with comma separated that is like apple, cat , ball, dog ,ant. please help me with this.
edit
publishingpost //nsmutable array contains all these object

-(ibaction)post
{
nsstring *str;
nsstring *str2 =@",";
for(int i = 0; i< [publishingpost count]; i++){
nsstring *str = [publishingpost objectAtIndex:i];
//append both str1, str2 to generate comma separated objects

}

A: use - (NSString *)componentsJoinedByString:(NSString *)separator instead:
- (IBAction)post {
   NSString * str = [publishingpost componentsJoinedByString:@", "];
}

A: Take a look at stringByAppendingString: or stringByAppendingFormat from here. It should be easy enough to do if you already have the Strings.
Declare an NSString object before the for loop (or use str) and append to that while going through the loop. And you're not supposed to declare str twice in your code. Might want to rename one of them.


text:
Q: Getting error 400 Bad Request when installing Angular CLI I am in the middle of installing Angular CLI using npm so I could use Angular 4 for some projects. however, Im getting 400 Bad Request error. does somebody also encountered this problem and got a solution on this? I already tried searching some relating to my problem but unfortunate to see one.
command:
npm config set proxy="myproxy.com:1234"
npm config set proxy-http="http://registry.npmjs.org/"
npm install -g @angular/cli

EDIT:
here is the debug log:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   '@angular/cli' ]
2 info using npm@5.6.0
3 info using node@v8.11.1
4 verbose npm-session a495756054a32527
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 400 https://registry.npmjs.org/@angular%2fcli 90ms
8 silly fetchPackageMetaData error for @angular/cli@latest 400 Bad Request: @angular/cli@latest
9 verbose stack Error: 400 Bad Request: @angular/cli@latest
9 verbose stack     at fetch.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\lib\fetchers\registry\fetch.js:42:19)
9 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
9 verbose stack     at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
9 verbose stack     at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
9 verbose stack     at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
9 verbose stack     at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
9 verbose stack     at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)
9 verbose stack     at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
9 verbose stack     at Immediate.Async.drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
9 verbose stack     at runCallback (timers.js:794:20)
9 verbose stack     at tryOnImmediate (timers.js:752:5)
9 verbose stack     at processImmediate [as _immediateCallback] (timers.js:729:5)
10 verbose cwd C:\
11 verbose Windows_NT 6.1.7601
12 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli"
13 verbose node v8.11.1
14 verbose npm  v5.6.0
15 error code E400
16 error 400 Bad Request: @angular/cli@latest
17 verbose exit [ 1, true ]

EDIT 2:
ok guys, I just now remove that 400 bad error with this set up:
npm config set proxy="http://username:password@proxyserverpac:proxyport/"
npm config set https-proxy="http://username:password@proxyserverpac:proxyport/"
npm config set http-proxy="http://username:password@proxyserverpac:proxyport/"
npm config set registry="http://registry.npmjs.org/"

but now I encounterred this error:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'info',
1 verbose cli   '@angular/cli' ]
2 info using npm@5.6.0
3 info using node@v8.11.1
4 verbose config Skipping project config: C:\Users\apamintuan/.npmrc. (matches userconfig)
5 silly mapToRegistry name @angular/cli
6 silly mapToRegistry scope (from package name) @angular
7 verbose mapToRegistry no registry URL found in name for scope @angular
8 silly mapToRegistry using default registry
9 silly mapToRegistry registry http://registry.npmjs.org/
10 silly mapToRegistry data { type: 'tag',
10 silly mapToRegistry   registry: true,
10 silly mapToRegistry   where: undefined,
10 silly mapToRegistry   raw: '@angular/cli',
10 silly mapToRegistry   name: '@angular/cli',
10 silly mapToRegistry   escapedName: '@angular%2fcli',
10 silly mapToRegistry   scope: '@angular',
10 silly mapToRegistry   rawSpec: '',
10 silly mapToRegistry   saveSpec: null,
10 silly mapToRegistry   fetchSpec: 'latest',
10 silly mapToRegistry   gitRange: undefined,
10 silly mapToRegistry   gitCommittish: undefined,
10 silly mapToRegistry   hosted: undefined }
11 silly mapToRegistry uri http://registry.npmjs.org/@angular%2fcli
12 verbose request uri http://registry.npmjs.org/@angular%2fcli
13 verbose request no auth needed
14 info attempt registry request try #1 at 12:46:50
15 verbose request id f486fd0b1ab9f374
16 http request GET http://registry.npmjs.org/@angular%2fcli
17 http 404 http://registry.npmjs.org/@angular%2fcli
18 verbose bad json <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
18 verbose bad json
18 verbose bad json
18 verbose bad json <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
18 verbose bad json <title>404 - File or directory not found.</title>
18 verbose bad json
18 verbose bad json
18 verbose bad json
18 verbose bad json

Server Error

18 verbose bad json

18 verbose bad json
<fieldset>
18 verbose bad json
404 - File or directory not found.

18 verbose bad json
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

18 verbose bad json  </fieldset>

18 verbose bad json

18 verbose bad json
18 verbose bad json
19 error registry error parsing json
20 verbose headers { 'content-type': 'text/html',
20 verbose headers   server: 'Microsoft-IIS/7.5',
20 verbose headers   date: 'Tue, 17 Apr 2018 19:46:50 GMT',
20 verbose headers   'content-length': '1245' }
21 verbose stack SyntaxError: Unexpected token < in JSON at position 0
21 verbose stack <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
21 verbose stack
21 verbose stack
21 verbose stack <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
21 verbose stack <title>404 - File or directory not found.</title>
21 verbose stack
21 verbose stack
21 verbose stack
21 verbose stack

Server Error

21 verbose stack

21 verbose stack
<fieldset>
21 verbose stack
404 - File or directory not found.

21 verbose stack
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

21 verbose stack  </fieldset>

21 verbose stack

21 verbose stack
21 verbose stack
21 verbose stack
21 verbose stack     at JSON.parse (<anonymous>)
21 verbose stack     at RegClient.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-registry-client\lib\request.js:243:23)
21 verbose stack     at Request._callback (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-registry-client\lib\request.js:216:14)
21 verbose stack     at Request.self.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\request\request.js:186:22)
21 verbose stack     at emitTwo (events.js:126:13)
21 verbose stack     at Request.emit (events.js:214:7)
21 verbose stack     at Request.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\request\request.js:1163:10)
21 verbose stack     at emitOne (events.js:116:13)
21 verbose stack     at Request.emit (events.js:211:7)
21 verbose stack     at IncomingMessage.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\request\request.js:1085:12)
21 verbose stack     at Object.onceWrapper (events.js:313:30)
21 verbose stack     at emitNone (events.js:111:20)
21 verbose stack     at IncomingMessage.emit (events.js:208:7)
21 verbose stack     at endReadableNT (_stream_readable.js:1064:12)
21 verbose stack     at _combinedTickCallback (internal/process/next_tick.js:138:11)
21 verbose stack     at process._tickCallback (internal/process/next_tick.js:180:9)
22 verbose cwd C:\Users\apamintuan
23 verbose Windows_NT 6.1.7601
24 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "info" "@angular/cli"
25 verbose node v8.11.1
26 verbose npm  v5.6.0
27 error Unexpected token < in JSON at position 0
27 error <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
27 error
27 error
27 error <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
27 error <title>404 - File or directory not found.</title>
27 error
27 error
27 error
27 error

Server Error

27 error

27 error
<fieldset>
27 error
404 - File or directory not found.

27 error
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

27 error  </fieldset>

27 error

27 error
27 error
28 verbose exit [ 1, true ]

could somebody guide me how I could overcome this problem?
EDIT 3:
this is now resolved.
none of the answers/comments below solved my problem.
however, thanks for all your inputs here. I appreciate it.
SOLUTION: I thought using the company's proxy server will do the trick but I didn't learned that fiddler is the only answer. I used it and set the proxy in npm to 'http://localhost:8888/' and the installation pushed through.

A: 1.open Command promt
2.run command "npm config edit"(open one file)
3.removed auth section "strict-ssl=true and 3-4 line"
and save file
Then install again angular cli

A: If you need a proxy to access the Internet, that you must make sure that the protocol (e.g. http/https) is specified for both http and https:
npm config set proxy="http://myproxy.com:1234"

Also, there is a big chance that you need to provide the same proxy for https as well:
npm config set https-proxy="http://myproxy.com:1234"

Also, run npm config set strict-ssl false to circumvent any possible certificate errors.

A: Try to clean the cache
$ npm cache clean

Then it's usually a good idea to uninstall/install it again.
Think of it as turning your computer off and on again.
$ npm uninstall -g @angular/cli
$ npm install -g @angular/cli


text:
Q: Swift - UI is reset when keyboard open I started to learn swift a few days ago and I have a big problem with the UI.
I have a function which sends data to a url and I want to update the UI when the data is arrived.
I tried to do it with dispatch async but when I tapped on a text filed and the keyboard is opened the UI is reset to the default UI as at the start point (in this case the btn returns to default y).
func loginConnect()
    {
        self.loginLoader.startAnimating();
        self.loginLoader.hidden = false;
        UIView.animateWithDuration(1, animations: {
            self.Loginbox.alpha = 0;
            self.loginBtn.alpha = 0;
        })
        var url1:NSURL = NSURL(string: "http://www.justaurl.com/login.php")!;
        println(url1);
        let request = NSMutableURLRequest(URL: url1);
        request.HTTPMethod = "POST";
        let postString = "user=username&pass=password";
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                println("error=\(error)")
                return
            }

            //println("response = \(response)")
            var error: NSError?
            var responseString:NSString = NSString(data: data!, encoding: NSUTF8StringEncoding)!;
            let data = responseString.dataUsingEncoding(NSUTF8StringEncoding);
            let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary;

            println(jsonData["0"] as String);
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                // Show the alert
                self.loginLoader.hidden = true;
                self.loginLoader.stopAnimating();
                UIView.animateWithDuration(1, animations: {
                    self.Loginbox.alpha = 1;
                    self.loginBtn.alpha = 1;
                }, completion:
                    {
                        completion in if 1 == 1
                        {
                            if((jsonData["0"] as String) == "error")
                            {
                                UIView.animateWithDuration(1, animations: {
                                    self.loginBtn.frame.origin.y = CGFloat(self.loginBtnDefaultY) + 15;
                                });
                            }

                        }
                        var timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("errorTxtAnimation"), userInfo: nil, repeats: false);
                    })
            })
            }
        }
        task.resume();
    }