text:
Q: Manipulate data from an async call I have two functions,
function getRequest(url, api_key, callback) {
    $.ajax({
        url: url,
        contentType: 'application/json',
        type: 'get',
        beforeSend: function(xhr){
            xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
        },
        success: function(response) {
            callback(response);
        },
        error: function(error) {
            console.log(error);
            document.getElementById("droplets").textContent = error;
        }
    });
}

function getDroplets(url, api_key) {
    var request = getRequest(url, api_key, function(response) {
        var droplets = response.droplets;
        var numDroplets = droplets.length;
        return {
            droplets: droplets,
            numDroplets: numDroplets
        };
    });
    alert(request);
}

I want to have another function, let's call it listDroplets, that will call getDroplets() and manipulate the data returned from it. I'm not sure how to do this because getDroplets has an asynchronous call within it.
EDIT: I have tried the following, but it still doesn't work.
async function listDroplets() {
    await getDroplets(api_url, api_key);
    alert(request.numDroplets);
}

A: Here are how your functions could return promise like objects that you can use in an async await function:
function getRequest(url, api_key, callback) {
  //to escape terrible jQuery Deferred and comfortably continue in Promise land
  // you can do
  // const deferred = $.ajax(...); return Promise.resolve(deferred)
  return $.ajax({//return promise like object
    url: url,
    contentType: 'application/json',
    type: 'get',
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
    }
  });
}

function getDroplets(url, api_key) {
  return getRequest(url, api_key)//return promise like object
  .then(function (response) {//
    var droplets = response.droplets;
    var numDroplets = droplets.length;
    return {
      droplets: droplets,
      numDroplets: numDroplets
    };
  })
  .catch(function (error) {//implement error if something goes wrong
    console.log(error);
    document.getElementById("droplets").textContent = error;
  });
}

async function listDroplets() {
  //depending on how old your jQuery is you may want to do this:
  // await Promise.resolve(getDroplets(api_url, api_key));
  const request = await getDroplets(api_url, api_key);
  //note that if something goes wrong then request is undefined (depending on jQuery version)
  alert(request.numDroplets);
}


text:
Q: Fileserver returning 404 What I really want to do is serve two directories as fileservers, /assets and /web/public.  For reference, here is my project structure:
/root
    /assets
    /web
        /public
        /src
        /templates
    main.go

When I run the server however, the /public routes return 404, while the assets are fine.  I've combed through the reference and through a bunch of tutorials, and everything I'm doing should be above the board.
package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "os"
    "path/filepath"

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    // here is where i set up the file servers
    publicHandler := http.FileServer(http.Dir(filepath.Join("web", "public")))
    r.PathPrefix("/pubic/").Handler(http.StripPrefix("/pubic/", publicHandler))

    assetHandler := http.FileServer(http.Dir("assets"))
    r.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", assetHandler))

    r.HandleFunc("/", s.HandleHome())

    port := fmt.Sprintf(":%d", 5123)
    http.ListenAndServe(port, r)
}

func (s *Server) HandleHome() http.HandlerFunc {
    tpl, err := template.New("").ParseFiles("web/templates/index.tpl")
    if err != nil {
        panic(err)
    }

    return func(w http.ResponseWriter, r *http.Request) {
        err = tpl.ExecuteTemplate(w, "index", nil)
        if err != nil {
            http.Error(w, "oops", http.StatusInternalServerError)
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scrapy: URL error, Program adds unnecessary characters(URL-codes) im using Scrapyto crawl a german forum: http://www.musikerboard.de/forum
It follows all subforums and extracts Information from threads.
The problem: During crawling it gives me an error on ultiple threadlinks:
2015-09-26 14:01:59 [scrapy] DEBUG: Ignoring response <404 http://www.musiker-board.de/threads/spotify-premium-paket.621224/%0A%09%09>: HTTP status code is not handled or not allowed

The URL is fine except for this part /%0A%09%09
It gives an 404 error.
I dont know why the program keeps adding the code to the end of the URL
Heres my code:
def urlfunc(value):
    value = value.replace("%0A", "")
    value = value.replace("%09", "")
    return value

class spidermider(CrawlSpider):
name = 'memberspider'
allowed_domains = ["musiker-board.de"]
start_urls = ['http://www.musiker-board.de/forum/'
              # 'http://www.musiker-board.de/'
              ]  # urls from which the spider will start crawling
rules = (
    Rule(LinkExtractor(allow=(r'forum/\w*',))),
    Rule(LinkExtractor(allow=(r'threads/\w+',),deny=(r'threads/\w+/[\W\d]+'),process_value=urlfunc), callback='parse_thread' ),
)

Does someone have a explanation why it keeps happening?(And a solution to it)
EDIT:
updated code

A: If you do some manual debugging and research you will find that the values at the end of the URL are meta-characters. %0A is a line feed, %09 is a horizontal tab: http://www.w3schools.com/tags/ref_urlencode.asp
Then if you enrich your urlfunc function with manual debug statements (and increase the log-level to INFO to see the results better) then you will see that the URLs do not end with these characters as a string just are converted when calling it as a website.
def urlfunc(value):
    print 'orgiginal: ', value
    value = value.replace('%0A', '').replace('%09', '')
    print 'replaced: ', value
    return value

This resulst in the following output:
orgiginal:  http://www.musiker-board.de/posts/7609325/

replaced:  http://www.musiker-board.de/posts/7609325/

orgiginal:  http://www.musiker-board.de/members/martin-hofmann.17/
replaced:  http://www.musiker-board.de/members/martin-hofmann.17/

The lines between the first result and the second one are there in the output because they have the meta-characters.
So the solution is to strip the values:
def urlfunc(value):
    return value.strip()

In this case you do not get any debug messages which tell you that the site was not found.

A: This may happen if whitespace and tabs are in the html code.
You could clean the URL by using process_value of LinkExtractor and do something like:
...
Rule(LinkExtractor(allow=(r'threads/\w+',)), callback='parse_thread', process_value=clean_url)
...

def clean_url(value):
    value = value.replace(u'%0A', '')
    value = value.replace(u'%09', '')
    return value


text:
Q: ASP.NET - How to add hyperlinks to pie chart sections? I have a pie chart that uses data returned from a business rules method. Is it possible to allow users to click on the segments of the pie chart by adding hyperlinks to each segment?
I know how to do this in the aspx of the pie chart, but the datasource and series of the data is based on the data returned from the method. Would you use something like: foreach series with a switch statement for the hyperlink?
How can I assign a hyperlink to the pie chart segments?

A: I worked out how to do this using a switch statement to assign a url and query string to specific segment names:
Point.Url = "/url?querystring"

A: to redirect from specific section of pie chart:
Chart1.Series[0].Points[0].Url="/url1";
Chart1.Series[0].Points[1].Url="/url2";
Chart1.Series[0].Points[2].Url="/url3";
to redirect from specific legends of pie chart:
Chart1.Series[0].Points[0].LegendUrl="/url1";
Chart1.Series[0].Points[1].LegendUrl="/url2";
Chart1.Series[0].Points[2].LegendUrl="/url3";
you can write:
Chart1.Series[0].Points[0].Url = Chart1.Series[0].Points[0].LegendUrl = "rptPendingBreakdown.aspx";

A: To redirect from the specific section of the pie chart.
Use:
Chart1.Series(0).Points(0).Url="/url1"

Chart1.Series(0).Points(1).Url="/url2"

Chart1.Series(0).Points(2).Url="/url3"

A: Try this one, it works fine for me
protected void QuestionResponseChart_DataBound(object sender, EventArgs e)
        {
            int points = QuestionResponseChart.Series[0].Points.Count;
            int i;
            for (i = 0; i <= points - 1; i++)
            {
                string txt = QuestionResponseChart.Series[0].Points[i].AxisLabel;
                QuestionResponseChart.Series[0].Points[i].Url = "SurveyList.ASPX?txt=" + txt;
            }
        }


text:
Q: CircleCI self hosted containers losing contact after 30 minutes We have some long running tests that moved into self hosted containers a while back to save on credits.  Recently, however, these tests have started dying (Infrastructure Failure) at the 30 minute mark.
Has anyone seen this and does anyone have an idea if it can be overcome.  Our local Ops team hasn't made any related changes which they think would be the cause of the 30 minute "disconnect".


text:
Q: Convert list inside pandas dataframe to list variable I have a .csv file structured as well:
    chan_id   spacecraft                           anomaly_sequences
      P-1       SMAP                 [[2149, 2349], [4536, 4844], [3539, 3779]]

I need to convert the list of list inside the cell anomaly_sequences to a variable, so I can loop inside it. I did it so:
list_labels = df['anomaly_sequences'].values.tolist()

but it converted all the cell in a single list, in fact if I try to print it I see it as:
['[[2149, 2349], [4536, 4844], [3539, 3779]]']

How can I correct it?

A: Not sure how you want to present your output, but if you want to convert your string into list of integers list, just do:
import json
var = "[[2149, 2349], [4536, 4844], [3539, 3779]]"
var = json.loads(var)
var

[[2149, 2349], [4536, 4844], [3539, 3779]]

And if you want to flatten the list of list, just use:
flat_list = [item for sublist in var for item in sublist]
flat_list

[2149, 2349, 4536, 4844, 3539, 3779]


text:
Q: How to erase directories that contain less than a certain number of files How can I find and delete subdirectories that contain less than 100 files (or 200 files)?
I have found and used the following command, but don't know how to delete the listed subdirectories. (I have over 1000 of such folders and subdirectories, can't do it by hand).
find . -maxdepth 5 -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \; | awk '$NF<=10'

thank you!

A: Below I have included the answer to your question, however I would like to stress that you need to exercise extreme caution with this command. The output of your original awk is being piped into rm -rf, this means that this command is forcibly removing all the folders listed.
Make sure that you are very careful as to where you run this because, if run in most places, this could cause massive problems or irreparable damage to the system.

find . -maxdepth 5 -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \; -print0 | awk '$NF<=10' | xargs rm -rf

The output of your original command is being piped into xarge rm -rf, xargs is converting the original output into arguments for another program, in this case, rm.
Excerpt from the manpage for rm for the two switches being used:
       -f, --force
          ignore nonexistent files, never prompt

       -r, -R, --recursive
          remove directories and their contents recursively

Piping directly into rm wouldn't work as it does not expect to receive file or folder names in that format.

A: In zsh:
for d (**/*(Nod/))
  ()(($#)) $d/*(NDoN.[100]) ||
  ()(($#)) $d/*(ND/Y1) ||
  rm -rf -- $d

Would delete the non-hidden directories that do not contain 100 regular files or more and do not contain subdirectories. That's processed depth-first so directories get a chance to be deleted if they have subdirectories that are to be deleted themselves.

*

***/ matches any level of subdirectories

*(Nod/) / (NDoN.[100]) / (ND/Y1): glob qualifiers to further qualify the glob based on other criteria:

*

*N: nullglob: don't treat it as a fatal error if there's no match, but let the glob expand to nothing instead.

*D: dotglob: don't ignore hidden (Dot) files.

*od: order depth first (leaves before the branch they're on)

*oN: do Not bother ordering the list

*/: restrict to files of type directory

*.: restrict to files of type regular

*[100]: selects the 100th match only (after sorting)

*Y1: stop searching after 1 match and don't even bother sorting.

*(){body} args: runs an anonymous function with args as arguments.

*(($#)) as the body of the anonymous function is an arithmetic expression that returns true if the expression evaluates to a number other than 0. So here if $#, the number of arguments to the anonymous function is non-zero.

A: Below script is dirty yet working solution.
Run this script on testing env before applying on working computer as it will delete the contents
cd desired_directory
for i in `find . -maxdepth 1 -type d | grep "/"`
do
   cd $i;
   j=`echo \`ls -l | wc -l\` | bc`
   [ $j -lt "100" ] && echo "Lesser than 100 files/directories in $i"
   cd ../
done

Here, you have to replace the echo statement with either rm -rf or mv.


text:
Q: how to Create Video using Image And mp3 file? I want to Create video using Image and mp3 or m4a file.
I try to use ffmpeg library but that library still not working for me.
I'm also try to use Media-codec and MediaMuxer.
if you have any new library or code then please suggest me.
Thanks in advance.


text:
Q: Change SQL Connection String I'm pretty new to vb and trying to play a little with Microsoft SQL Server and VB.NET.
I built a Form that shows some data from the SQL-Server-Database. I have two SQL-Servers, one is the Test-System, the other a Live-System. First I grabbed the Data from the Test-System. Now I want to switch to the Live-Server. So I Changed the Connection-String to the live-System.
Strange thing:
If I run the the program, an empty form comes up. If I Change the Connection String back to the Test-System, all works perfectly fine.
Server, User and Password are 100% correct. The Servers are an exact copy of each other. Query and Connection in MS SQL Management Studio are working perfectly fine on both systems.
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=Sever1\SRV;Database=DB1;User=User1;Pwd=Pwd1"}
Public SQLCmd As SqlCommand
Public SQLExecQ As SqlDataReader

Function RunQuery(Query As String) As SqlDataReader
 SQLCon.Open()
 SQLCmd = New SqlCommand(Query, SQLCon)
 Return SQLCmd.ExecuteReader()
End Function

    SQLExecQ = SQL.RunQuery("SELECT * FROM table1 ORDER BY col1 ASC")

    Do While SQLExecQ.Read()
      'Code
    Loop

    SQLExecQ.Close()
    SQLCon.Close()

Any ideas?


text:
Q: Multiple script tags variable conflict? I have multiple script tags in a web page.  Will having the same variable name in more than one script tag cause issues with the variables getting the wrong value from an above script tag?
<script type="text/javascript">
   var current = 0;
</script>

<script type="text/javascript">
   var current = 1;
</script>

Will the first current cause issues with the second occurence?

A: Yes it will. There is only one global execution context, doesn't matter how many <script> nodes you have in your HTML markup.
So in this particular example, current gets initialzed on the window object with 0 and then gets overwritten with 1.

A: You won't ever run into a situation where code that's executed immediately after the var current = 1 in your second <script> tag will be using current with a value other than 1. To provide a very basic example:
<script type="text/javascript">
   var current = 0;
   alert(current); // will always alert 0
</script>

<script type="text/javascript">
   var current = 1;
   alert(current); // will always alert 1, never 0
</script>

That should answer the "cause issues with the variables getting the wrong value from an above script tag" aspect of the question.


text:
Q: I want call php page by clicking on a button but I want to verify it first through javascript that entered value is correct or not <head>
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>
</head>

I'm using this code for verify entered value and after verification I want call php page to get the entered value for further task
<body>
<form>
    <input type="text" id="search" onsubmit="search()" name="bg">
</form>
</body>

A: Not 100% sure what your asking!
If you are trying to get the value of the input field you need to change your document.getElementid("search");
To document.getElementid("search").value;
As this will be a string you will also need to change your if statement to make sure the value is equal to a 'A' ||'B'

A: Try this code : why you are not using opening script tag

< script > tag after < head >

<head>
</script>
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>
</head>

A: <head>
<script>
    function search_bloodgroup(){

        var bloodgroup = document.getElementById("search").value;
        if(bloodgroup ==="a+"|| bloodgroup ==="A+" || bloodgroup ==="aplus" || bloodgroup ==="APLUS"){
            alert("true");
            return true;
        }
        else {
            alert("Enter Correct");
            return false;
            }
    }
</script>
</head>
<body>
<form onsubmit="search_bloodgroup()" action="">
    <input type="text" id="search" name="bg"></input>
    <input type='submit'></input>
</form>

</body>
</html>

This works fine hopefully this will help.


text:
Q: how to clear all list in ionic2 I'm working in ionic 2 project, created swipe to delete each items working fine and also need click button delete all items How can I delete all items from a list in angular 2?
<button ion-button clear>Clear All</button>
<ion-item-sliding *ngFor="let note of notes">
          <ion-item>
              {{note.title}}
          </ion-item>
          <ion-item-options>
              <button (click)="deleteNote(note)" danger>
                  <ion-icon name="trash"></ion-icon>
              </button>
          </ion-item-options>
        </ion-item-sliding>

file.ts
constructor( public viewCtrl: ViewController ) {
    this.notes = [
      { title: 'This is notification swipe to delete' },
      { title: 'This is notification swipe to delete' }
      ];
  }
deleteNote(note){

        let index = this.notes.indexOf(note);

        if(index > -1){
            this.notes.splice(index, 1);
        }
    }

A: You can create a clear() method like this
public clear(): void {
  this.notes = [];
}

And call it from the view
<button ion-button clear (click)="clear()">Clear All</button>


text:
Q: React google map wont update styles after changing theme (component re-render)? I have a custom theme in my website (light/dark) and I have a custom hook for that also.
I put google map (react-google-maps) custom style in a useMemo and set theme as the dependancy but when I change theme it seems that map component doesn't re-render and apply new colors.. I tried to debug but no luck. here's my implementation:
export const MapMarkerSelection = compose(
    withProps({
        googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${API_KEY_MAP}&libraries=geometry,drawing,places`,
        loadingElement: <div style={{height: `100%`}} />,
        containerElement: (
            <div style={{height: `400px`, margin: `8px 0 20px`, borderRadius: `0.5rem`, overflow: 'hidden'}} />
        ),
        mapElement: <div style={{height: `100%`}} />,
    }),
    withScriptjs,
    withGoogleMap,
)((props) => {
    const mapRef = useRef();
    const theme = useTheme(); //here is mu custom hook (no issue with this it work fine in other components)

    useEffect(() => {
        setLatMarker(props.markerPosition.latitude);
        setLngMarker(props.markerPosition.longitude);
        mapRef.current.panTo({
            lat: props.markerPosition.latitude,
            lng: props.markerPosition.longitude,
        });
    }, [props.markerPosition, props.markerPosition.latitude, props.markerPosition.longitude]);

    const [latMarker, setLatMarker] = useState(props.markerPosition.latitude);
    const [lngMarker, setLngMarker] = useState(props.markerPosition.longitude);
    const setCallback = useCallback(
        (latLng) => {
            if (props.onSelectPosition) {
                props.onSelectPosition({latitude: latLng.lat(), longitude: latLng.lng()});
                setLatMarker(latLng.lat());
                setLngMarker(latLng.lng());
                mapRef.current.panTo({
                    lat: latLng.lat(),
                    lng: latLng.lng(),
                });
            }
        },
        [props],
    );

    const mapStyle = useMemo(() => {
        console.log('here');
        return [
            {
                featureType: 'water',
                elementType: 'geometry',
                stylers: [
                    {
                        color: theme.BACKGROUND_COLOR, //here I set water color to dark for dark theme and blue for lighr theme
                    },
                    {
                        lightness: 17,
                    },
                ],
            },
            {
                featureType: 'landscape',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#f5f5f5',
                    },
                    {
                        lightness: 20,
                    },
                ],
            },
            {
                featureType: 'road.highway',
                elementType: 'geometry.fill',
                stylers: [
                    {
                        color: '#ffffff',
                    },
                    {
                        lightness: 17,
                    },
                ],
            },
            {
                featureType: 'road.highway',
                elementType: 'geometry.stroke',
                stylers: [
                    {
                        color: '#ffffff',
                    },
                    {
                        lightness: 29,
                    },
                    {
                        weight: 0.2,
                    },
                ],
            },
            {
                featureType: 'road.arterial',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#ffffff',
                    },
                    {
                        lightness: 18,
                    },
                ],
            },
            {
                featureType: 'road.local',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#ffffff',
                    },
                    {
                        lightness: 16,
                    },
                ],
            },
            {
                featureType: 'poi',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#f5f5f5',
                    },
                    {
                        lightness: 21,
                    },
                ],
            },
            {
                featureType: 'poi.park',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#dedede',
                    },
                    {
                        lightness: 21,
                    },
                ],
            },
            {
                elementType: 'labels.text.stroke',
                stylers: [
                    {
                        visibility: 'on',
                    },
                    {
                        color: '#ffffff',
                    },
                    {
                        lightness: 16,
                    },
                ],
            },
            {
                elementType: 'labels.text.fill',
                stylers: [
                    {
                        saturation: 36,
                    },
                    {
                        color: '#333333',
                    },
                    {
                        lightness: 40,
                    },
                ],
            },
            {
                elementType: 'labels.icon',
                stylers: [
                    {
                        visibility: 'off',
                    },
                ],
            },
            {
                featureType: 'transit',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#f2f2f2',
                    },
                    {
                        lightness: 19,
                    },
                ],
            },
            {
                featureType: 'administrative',
                elementType: 'geometry.fill',
                stylers: [
                    {
                        color: '#fefefe',
                    },
                    {
                        lightness: 20,
                    },
                ],
            },
            {
                featureType: 'administrative',
                elementType: 'geometry.stroke',
                stylers: [
                    {
                        color: '#fefefe',
                    },
                    {
                        lightness: 17,
                    },
                    {
                        weight: 1.2,
                    },
                ],
            },
        ];
    }, [theme.BACKGROUND_COLOR]);

    return (
        <GoogleMap
            ref={mapRef}
            defaultOptions={{
                styles: mapStyle,
            }}
            defaultZoom={12}
            defaultCenter={{lat: latMarker, lng: lngMarker}}
            onClick={({latLng}) => setCallback(latLng)}
        >
            <Marker position={{lat: latMarker, lng: lngMarker}} draggable onDragEnd={({latLng}) => setCallback(latLng)} />
        </GoogleMap>
    );
});

only if I refresh the page the new theme for map applies. how can I solve this?

A: Does theme change constantly? If not, just add a key to GoogleMap, keep in mind this will cause a full rerender of the map, maybe not what you want if the user can move the map around.
Also, check the documentation for the library, or post it here if possible, it may be that the defaultOptions prop is internally cached by the component to prevent rerenders. Also, when using memo, avoid stuff like prop={{memoizedValue}} since your're still creating a new object everytime, intead go for prop={memoizedValue}.
<GoogleMap
  ...
  key={theme.BACKGROUND_COLOR}
/>


text:
Q: substract two vars and add result to mysql database I have the result of two request, that contains numbers decimal 8,2.
I try to make a substraction of this var and to add result to databse.
Usualy I do like that $var1-$var2
So I have the following request:
$requete= 'UPDATE `decompte` SET
principal_s         = '.$pay['principal_s']-$donnees2['principal_s'].',
clause_penale_s     = '.$pay['clause_penale_s']-$donnees2['clause_penale_s'].',
domages_interets_s  = '.$pay['domages_interets_s']-$donnees2['domages_interets_s'].',
art700_cpc_s        = '.$pay['art700_cpc_s']-$donnees2['art_700_cpc_s'].',
art475_1_cpp_s      = '.$pay['art475_1_cpp_s']-$donnees2['art475_1_cpp_s'].',
art_441_6_cc_s      = '.$pay['art_441_6_cc_s']-$donnees2['art_441_6_cc_s'].',
frais_ar_s          = '.$pay['frais_ar_s']-$donnees2['frais_ar_s'].',
agios_s             = '.$pay['agios_s']-$donnees2['agios_s'].',
depens_s            = '.$pay['depens_s']-$donnees2['depens_s'].',
frais_execution_s   = '.$pay['frais_execution_s']-$donnees2['frais_execution_s'].',
contrib_aid_juridiq_s   = '.$pay['contrib_aid_juridiq_s']-$donnees2['contrib_aid_juridiq_s'].',
frais_greffe_s          = '.$pay['frais_greffe_s']-$donnees2['frais_greffe_s'].'';

mysql_query($requete) or die(__LINE__.mysql_error().$requete);

The trouble is that it display to me a mistake, it says:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-5000' at line 1-5000.

I'm a bit lost I really do not see what happened there.
anykind of help or advice will be much appreciated

A: Put all the subtraction inside brackets. Eg:
principal_s         = '.($pay['principal_s']-$donnees2['principal_s']).',
clause_penale_s     = '.($pay['clause_penale_s']-$donnees2['clause_penale_s']).',

PHP first executes the concatenation, then it evaluates the arithmetic operation!

A: It's an interesting issue with PHP.
The concatenation operator is evaluated before the subtraction operator.
If you wrap your lines in brackets, it will work:
principal_s         = '.($pay['principal_s']-$donnees2['principal_s']).',

This issue caused me a couple of hours of stress a month or so back before I figured out what was causing it.


text:
Q: Excel - Auto increment value based on string search I've got a set of data that needs updating to use the same "reference" value (auto-incrementing by .1 with each record found) where a name matches against the first two words.
Please see below for an example table with the desired format required below - is there a way to do this via an automated function in Excel?
Alternatively, I can use SQL Server to do this if easier.
Many thanks in advance

Name
Current Reference
DESIRED Reference

First Name
1001.1
1001.1

First Name Also
2123.1
1001.2

First Name Also With More Text
3456.1
1001.3

Second Name
4567.1
4567.1

Second Name Also
1232.1
4567.2

Second Name Also With More Text & Symbols
5890.1
4567.3


text:
Q: Proving that if $f'$ has at most $n-1$ zeros, then $f$ has at most $n$ zeros Is this proof correct?
The problem is the following.

Let $n$ be a natural number. Suppose that the function $f:\mathbb{R}\to\mathbb{R}$ is differentiable and that the following equation has at most $n-1$ solutions:
  $$f'(x)=0, \quad x \in \mathbb{R}.$$
  Prove that the following equation has at most $n$ solutions:
  $$f(x)=0,\quad x \in \mathbb{R}.$$

My proof is:
Let $f'(x)=0$ have solutions $x_1$, $x_2,\ldots ,x_{n-1}$.
since
$$f'(x_1)=\lim\limits_{{x}\to{x_1}}\frac{f(x)-f(x_1)}{x-x_1} = 0$$
and doing so, $f(x)=f(x_{n-1})$
Therefore $f(x)=f(x_1)=f(x_2)=\cdots=f(x_{n-1})$.
Let $x_n$ be one of solutions of $f(x)=0$.
$$0=f(x_n)=f(x_1)=f(x_2)=\cdots=f(x_{n-1}),$$
so $f(x)=0$ has solutions like $x_1$, $x_2,\ldots, x_n$.
If there is wrong part, please let me know.

A: Use the mean value theorem.
Fix $n=3$. (The argument generalizes for arbitrary $n \in \mathbb{N}$).
Suppose $f(x)=0$ has more than three (distinct) solutions, say $x_1 < x_2 < x_3 < x_4$. Then the mean value theorem (Rolle's Theorem) implies that there exist $c, d, e \in \mathbb{R}$ such that $x_1 < c < x_2 < d < x_3 < e < x_4$ and $f'(c)=f'(d)=f'(e)=0$, contradiction.

A: I'm not that clear on what you're doing, but your solution looks wrong. Just the conclusion that $f$ is zero at the the zeros of $f'$ (you have $n$ of them, by the way) is clearly false in general. You seem to be trying to do some variable point argument with $x$, and using the fact that the limit is zero to conclude that individual terms are zero.
A valid solution is to note that there is a zero of $f'$ between any two zeros of $f$ by the mean value theorem.

A: *

*You cannot simply assume that $f'(x)$ is a polynomial. That is not given in the problem, and there are plenty of other functions that can have a specific number of zeros.  (Also, the problem says that $f'(x)=0$ has at most $n-1$ solutions, not that it has exactly $n-1$ solutions, yet you assume it has this maximum).

*Even if you know that $f'(x)$ is a polynomial, you do not know that the degree is at most $n-1$; it's possible for a polynomial to have degree strictly larger than $k$, and yet have only $k$ distinct real roots.

*It's false that the fact that $f'(x_1)=0$ implies that $f(x_1)=0$.

*The statement "and doing so, $f(x)=f(x_{n-1})$" makes no sense to me.

*You never showed that there are at most $n$ solutions to $f(x)=0$.

*You seem to believe that the same numbers that are zeros of the derivative are zeros of the original function. This is not true, even for polynomials. $f(x) = x^2 - 3x + 2$ has zeros at $x=1$ and $x=2$, but the zero of $f'(x) = 2x-3$ is at $x=\frac{3}{2}$.
So, I would say that pretty much all of this argument is incorrect.
Suggestion. Either use the Mean Value Theorem, or use Darboux's Theorem.
Here's how an argument using the latter would go:
Suppose the zeros of the derivative are $a_1\lt a_2 \lt\cdots \lt a_{n-1}$. By Darboux's Theorem, the derivative cannot change signs except at the points where it is equal to $0$. That means, for example, that it is either always positive or it is always negative on $(-\infty,a_1)$. That means that $f(x)$ is strictly monotone on $(-\infty,a_1)$: either strictly increasing, or strictly decreasing. How many zeros can a strictly monotone function have? So, how many zeros can $f(x)$ have on $(-\infty,a_1)$?
What about $(a_1,a_2)$? $(a_2,a_3)$? Etc.
But I suspect you'll want to use the Mean Value Theorem; Darboux's Theorem is not often covered in basic analysis courses.

A: Suppose $f(x)=0$ has more than n solutions and then show that then $f'(x)=0$ would have more than $n-1$ solutions.
It's a proof by contrapositive.
Instead of showing that $a\implies b$, you show that $\neg b \implies \neg a$.


text:
Q: Issue setting returned text to variable within repeat loop - OS X 10.9.x The goal of this script is to:

*

*Ask the user how many text replacement (System Preferences>Keyboard>Text) shortcuts they'd like to have. The text returned is set to my variable "gTextReplacementNum" as number. See my second handler "HowMany()"

*Have the user provide the text replacement shortcut and the text to do the replacing for the number of shortcuts they wanted. See my third handler "GetText()"

*Take the user provided text contained in a variable to create a new AppleScript doc that does all the heavy lifting for them. Code not yet written; not within scope of question.

*Then they have a personalized AppleScript Application Bundle they may launch on their Mac to auto-populate the text replacement preferences pane.
I am having trouble getting this to work properly. I need the loop to keep adding the answers to a variable as a list or to a variable that increments its name according to the loop instance (e.g. TextReturned_i, TextReturned_i+1, etc).
Have I adequately explain this?
global gTextReplacementNum
set gTextReplacementNum to 0

# Main Logic Begins

try

    Start()

    HowMany()

    GetText()

on error errText number errNum
    display alert "Error " & errNum message errText

end try

# Main Logic Ends

# Handlers Begin

-- First Handler
on Start()
    display alert "Automated Text Replacement v1.0" message "Created by: Me
myemail@domain.com" buttons {} giving up after 4
    display alert "About" message "This app will have you provide a text 'short cut' to replace with and replacement text. It then compiles all this into an application that can be run on any Mac.

    Would you like to continue?" buttons {"No", "Yes"} cancel button 1 default button 2
end Start

-- Second Handler
on HowMany()
    display dialog "How many text replacement shortcuts would you like?

    Please enter numericals only. (1, 2, 3)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
    copy the result as list to {ButtonPressed, TextReturned}
    set gTextReplacementNum to TextReturned as number
end HowMany

-- Third Handler
on GetText()
    repeat with i from 1 to gTextReplacementNum as number
        display dialog "What text would you like to replace?
        (this is your shortcut)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
        set TextShortcut to text returned of result as list

        display dialog "What is the replacement text?
        (this is what the shortcut fills out)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
        set TextReplaced to text returned of result as list
    end repeat
end GetText

# Handlers End

A: In your GetText() handler, you are replacing the value TextShortcut and TextReplaced each time. You need to
set aList to aList & newValue

to build a list in a repeat loop.
Also, as is, this handler never returns the value of these two lists. So, I'd suggest, using your scheme, make these two variables globals as well.
So, the full changes are:
1. Add to the declarations:
global gTextReplacementNum
global gTextShortcut
global gTextReplaced

set gTextReplacementNum to 0
set gTextShortcut to {}
set gTextReplaced to {}

and 2. edit your GetText() handler:
-- Third Handler
on GetText()
    repeat with i from 1 to gTextReplacementNum as number
        display dialog "What text would you like to replace?
        (this is your shortcut)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
        set gTextShortcut to gTextShortcut & (text returned of result)

        display dialog "What is the replacement text?
    (this is what the shortcut fills out)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
        set gTextReplaced to gTextReplaced & (text returned of result)
    end repeat
end GetText

An alternate method would be to read a tab delim file and work from that with a standard script. Something like:
property fileName : "shortcuts.txt"

set filePath to (path to desktop as string) & fileName
set theData to read file filePath

set theRecords to paragraphs of theData
set oldDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab

repeat with thisPair in theRecords
    set {theShortcut, theReplacement} to text items of thisPair
    setKeyboardPref(theShortcut, theReplacement)
end repeat
set AppleScript's text item delimiters to oldDelim

on setKeyboardPref(theShortcut, theReplacement)
    -- set up the pair
    display dialog theShortcut & return & theReplacement
end setKeyboardPref


text:
Q: How To Use Formula In Order To Find The Recommended Company In Excel I need to know whether these is a formula to find the selected company using excel.
For Example, I use the Min formula to find the lowest value between 3 selected company. But what I want is to auto select the company name with the lowest value.
Eg.

Any help is really much appreciated.

A: With Excel365 you can use XLOOKUP() in this way.
=XLOOKUP(MIN(A2:C2),A2:C2,A1:C1)

You can also use INDEX/MATCH as @BigBen suggested.
=INDEX(A1:C1,,MATCH(MIN(A2:C2),A2:C2,0))


text:
Q: factorization of an expression involving gamma function Does the equation $\Gamma(x+1/2)\Gamma(x-1/2)=\Gamma(x+iy)\Gamma(x-iy)$, where $\Gamma(z)$ is the Gamma function and $i=\sqrt{-1}$, have any solution assuming $x,y$ are both real and $x>1/2$?
This is needed to factorize the expression:
$$
1-\frac{\Gamma(x+iy)\Gamma(x-iy)}{\Gamma(x+1/2)\Gamma(x-1/2)}.
$$
Is there any way factorize it? This expression arises in a half-plane Wiener-Hopf equation half-plane.

A: By the log-convexity property of $\Gamma$, we have
$$
\Gamma^2(x)<\Gamma\left(x-\frac{1}{2}\right)\Gamma\left(x+\frac{1}{2}\right)\tag{1}
$$
For $x>\frac{1}{2}$.
On the other hand,
$$
|\Gamma(x+iy)|=\left\vert\int_0^\infty t^{x-1+iy}e^{-t}dt\right\vert\leq
\int_0^\infty \left\vert t^{x-1+iy}e^{-t}\right\vert dt=
\int_0^\infty   t^{x-1}e^{-t}  dt=\Gamma(x)\tag{2}
$$
Combining (1) and (2) we see that, for $x>\frac{1}{2}$ and $y\in\Bbb{R}$, we have
$$
\Gamma(x+iy)\Gamma(x-iy)=|\Gamma(x+iy)|^2\leq\Gamma^2(x)<\Gamma\left(x-\frac{1}{2}\right)\Gamma\left(x+\frac{1}{2}\right).
$$
So, there is no $(x,y)\in[\frac{1}{2},+\infty)\times \Bbb{R}$ such that
$$\Gamma(x+iy)\Gamma(x-iy)=\Gamma\left(x-\frac{1}{2}\right)\Gamma\left(x+\frac{1}{2}\right)$$


text:
Q: enemies and slopes How would you achieve a certain slope for a moving object ?  I'm trying to get a enemy to spawn of the screen at point x,y  and fly by itself across the screen to a new x,y while aslo adding a slope so it looks like it's swooping downward,straight, or upwards.. something like that. Right now I only have the knowledge of spawning and moving my enemies in a certain direction and don't know what to look up from here.

A: If you want to move in a strait line between to points then you could calculate the delta X and delta Y as:
DX = X2-X1;
DY = Y2-Y1;

Then if you want to move a specific distance (speed/frame), normalize the length using the Pythagorian theorem:
HYP = DX*DX + DY*DY;
HYP = sqrt(HYP);
DX = MoveD * DX/HYP;
DY = MoveD * DY/HYP;

Then:
// Move Distance (MoveD) From X1,Y1 to X2,X2 each screen update.
if ((abs(X2-X)<DX)&&(abs(Y2-Y)<DY))
{
  X = X + DX;
  Y = Y + DY;
} else
// STOP

"Swooping" can be done by changing the endpoint dynamically.  Start with the end point in front of the "Target" and Move through the target and up to create a "swooping" motion.  Add a "Speed bias" such that it accelerates moving down and decelerates moving up.
This can also be addapted to integer math using a variation on Bresenham's line drawing algorthm or DDA.


text:
Q: Horizontal menus in css/HTML Hi so I am creating a website, but I am troubled a bit with the footer menu - It only becomes horizontal when I use float:left (but after crossing a certain point it creates a new line). If I use anything other than float:left it becomes vertical. My goal is to make it all on a single line. Example in the image (my goal is to make the footer menu horizontal like my top menu) https://i.gyazo.com/61f2f5f7c0e6d98ad181364365163dd4.png
Here is the code I used. Footer code based on menu code:
#menuPan{width:736px; height:36px; position:relative}

#menuPan ul.menu{position:absolute; top:0; left:0; width:736px; overflow: hidden; background-color:#3f3f3f;}
#menuPan ul.menu li{height:36px; margin-right:5px; float:left; font-size:large; }
#menuPan ul.menu li a{height:36px; display:block; display: inline-block; color: white; text-align: center; padding: 8px 10px; text-decoration: none;}
#menuPan ul.menu li a:hover{height:36px; background-color: #6d6d6d;}

And my footer code:
#footer ul.footertest li{height:20px; float:left; font-size:large;}
#footer ul.footertest li a{height:20px; display:block; display: inline-block;  color:darkslategrey; text-align: center; padding: 8px 10px; text-decoration: none;}
#footer ul.footertest li a:hover{height:20px; background-color: #6d6d6d;}

A: Try applying
display: inline-block;


text:
Q: Cup-squares in the mod 2 cohomology of a cell complex embedded in 3-space If a 3-dim'l cell complex $X$ is embedded in $\mathbb{R}^3$, no subcomplex of $X$ is a real projective plane.  Intuitively, this suggests that all cup-squares vanish in $H^*(X;\mathbb{Z}_2)$.  Is this statement true? If so, can you provide a reference?

A: It is true.  Let's first assume that $X$ is a finite complex.  Then by Alexander duality, $H^2(X;\mathbb{Z})=H_0(S^3\setminus X,\mathbb{Z})$ must be torsion-free.  Now the squaring map $H^1(X;\mathbb{Z}/2)\to H^2(X;\mathbb{Z}/2)$ coincides with the Bockstein map.  This means that if the squaring map is nonzero, then $H_1(X;\mathbb{Z})$ must have $\mathbb{Z}/2$ as a direct summand.  But then $H^2(X;\mathbb{Z})$ would have $\mathbb{Z}/2$ as a summand, and in particular cannot be torsion-free.
Now let $X$ be arbitrary, and write $X=\bigcup X_n$ as a union of finite complexes; from now on we only use $\mathbb{Z}/2$ coefficients.  Then $H^1(X_n)$ is finite for all $n$, so $\lim^1 H^1(X_n)=0$.  It follows that the map $H^2(X)\to\lim H^2(X_n)$ is an isomorphism.  Now for any $x\in H^1(X)$, the image of $x^2$ in $H^2(X_n)$ must be 0 for all $n$ by the previous paragraph.  Thus $x^2=0$.


text:
Q: IoC Windows Service Architecture I am traditionally an SQL guy. I have a bunch of C# experience under my belt, but these have all tended to be tooling or customisation projects.
I am now tasked with writing a application that does the following...

*

*Runs as a windows service

*Watches for files, and when they arrive, loads them to a DB

*Monitor the DB for newly loaded files

*Perform some complex parsing on those files (involves aggregating db records)

*Additional interfaces are required (web site for query parsed data etc)

*Multiple file types must be supported, multiple parsers must be supported.

So, this is my first foray into IoC and I am trying my best to do things corretly. I am using Autofac and am quite comfortable with the concepts. My issue is in understanding the composition root, when it is ok to pass a container, what do I replace my traditional notion of a 'factory' with.
My app is structured with an L2S model and a generic repository interface over that. I use an Autofac module to register the concrete types. I have a logger and use a module to register the concrete types also. In my test console app (which will be replaced by a windows service host), I create a container and register the logger and dal modules etc. I can then resolve my file watching classes using constructor injection to inject the logger, and repository. I also inject a queue object (in my case a memory backed queue, but could be a db queue) onto which new files are enqueued (producer). At the other end of the queue, I need a consumer. So, depending on the type of file being dequeued, I need to use a different loader class. I would of historically use a factory pattern to return the appropriate concrete class. Since the loader class needs to have a logger and appropriate repository injected into it, I cannot see how to create an instance of the appropriate loader class to handle the item coming off the queue without giving my factory class a reference to the IoC container. I know I can inject various item handlers into my consumer class, but say I had 50 file types, or 100, that is impractical.
After I understand how to do this, I need to do something similar to watch for new parsing jobs (entries in a db table) and process those, but I am assuming it'll follow a similar pattern to the above.
Any advice folks? I am this far (small distance) away from binning my C# and going to SSIS for the file loading, then hacking some nasty parser code in SSIS. Please help a C# learner.

A: I have realised that I can just new up a bunch of loader classes and put them in a dictionary and pass that into the constructor. That allows me to ask for a loader by name.

A: It sounds like you're trying to container construct every entity in your application - use DI sparingly and only where you need substitutable behaviour, there's nothing wrong with plain old "new" where appropriate.
Another suggestion could be to mark your custom file loaders with an interface, say IFileLoader, run through all loaded assemblies and (using reflection) detect the implemented loaders. Then, assemble all the loaders in a chain of responsibility so that if one loader can't process the file type in question, it passes on the responsibility to the next. This way, it will be easy to add new loaders and the file watching part is clearly separated from the loading part. The COR pattern is not a must, the functionality can of course be provided with a simple loop.

A: Here's my take on how you as a newbie should start.
Start writing your classes. All dependencies on other classes are taken in the constructor.
Since you never new up a class to get an instance at any other point than when you are constructing your objects, it will make your program look similar to this:
static void Main(..) {
  var s1 = ...;
  var s2 = ...;
  var sn = ... SN(s1, s2, ..);
  sn.Wait();
}

Now you can replace all ... with registrations in your container. You don't use factory classes at all; an IoC container IS your factory. And then you replace the very root initialisation:
var sn = container.Resolve<SN>();

Now you are using IoC. Don't use a dictionary.


text:
Q: Parsing JSON output for Discord Bot in Python Summary
I'm currently getting the first object of a JSON array dumping into Discord but I only want a portion of the data, specifically teams. I believe I need to edit line 50 return(odds_json['data'][0]), can anyone help me with pulling this specific piece of data?
Here's said dump:

{'id': '19c709db17e33a20f7c88af1a119cef1', 'sport_key': 'basketball_nba', 'sport_nice': 'NBA', 'teams': ['Atlanta Hawks', 'New York Knicks'], 'commence_time': 1622394647, 'home_team': 'Atlanta Hawks', 'sites': [{'site_key': 'fanduel', 'site_nice': 'FanDuel', 'last_update': 1622399415, 'odds': {'h2h': [-1350, 700]}}, {'site_key': 'betmgm', 'site_nice': 'BetMGM', 'last_update': 1622399373, 'odds': {'h2h': [-650, 475]}}, {'site_key': 'betrivers', 'site_nice': 'BetRivers', 'last_update': 1622399389, 'odds': {'h2h': [-910, 540]}}, {'site_key': 'draftkings', 'site_nice': 'DraftKings', 'last_update': 1622399388, 'odds': {'h2h': [-835, 525]}}, {'site_key': 'sugarhouse', 'site_nice': 'SugarHouse', 'last_update': 1622399399, 'odds': {'h2h': [-1000, 575]}}, {'site_key': 'barstool', 'site_nice': 'Barstool Sportsbook', 'last_update': 1622399403, 'odds': {'h2h': [-1000, 575]}}, {'site_key': 'unibet', 'site_nice': 'Unibet', 'last_update': 1622399400, 'odds': {'h2h': [-1000, 575]}}, {'site_key': 'betfair', 'site_nice': 'Betfair', 'last_update': 1622399405, 'odds': {'h2h': [-500, 470], 'h2h_lay': [-476, 500]}}, {'site_key': 'pointsbetus', 'site_nice': 'PointsBet (US)', 'last_update': 1622399407, 'odds': {'h2h': [-620, 410]}}, {'site_key': 'williamhill_us', 'site_nice': 'William Hill (US)', 'last_update': 1622399389, 'odds': {'h2h': [-650, 450]}}, {'site_key': 'foxbet', 'site_nice': 'FOX Bet', 'last_update': 1622399401, 'odds': {'h2h': [-909, 450]}}, {'site_key': 'gtbets', 'site_nice': 'GTbets', 'last_update': 1622399392, 'odds': {'h2h': [-946, 543]}}, {'site_key': 'caesars', 'site_nice': 'Caesars', 'last_update': 1622399398, 'odds': {'h2h': [-455, 320]}}, {'site_key': 'bovada', 'site_nice': 'Bovada', 'last_update': 1622399102, 'odds': {'h2h': [120, -160]}}, {'site_key': 'mybookieag', 'site_nice': 'MyBookie.ag', 'last_update': 1622399393, 'odds': {'h2h': [-285, 210]}}], 'sites_count': 15}

And here's the .py file.
import discord
import os
import requests
import json

api_key = os.environ['API_KEY']

client = discord.Client()

def get_odds():
  sports_response = requests.get('https://api.the-odds-api.com/v3/sports', params={
      'api_key': api_key
  })

  sports_json = json.loads(sports_response.text)

  if not sports_json['success']:
      print(
          'There was a problem with the sports request:',
          sports_json['msg']
      )

  else:
    print('Keep it 200')

  sport_key = 'basketball_nba'

  odds_response = requests.get('https://api.the-odds-api.com/v3/odds', params={
      'api_key': api_key,
      'sport': sport_key,
      'region': 'us', # uk | us | eu | au
      'mkt': 'h2h', # h2h | spreads | totals
      'oddsFormat': 'american'
  })

  odds_json = json.loads(odds_response.text)
  if not odds_json['success']:
      print(
          'There was a problem with the odds request:',
          odds_json['msg']
      )

  else:
      # odds_json['data'] contains a list of live and
      #   upcoming events and odds for different bookmakers.
      # Events are ordered by start time (live events are first)
      print(
          'Successfully found {} events'.format(len(odds_json['data']))
      )
      return(odds_json['data'][0])

      # Check your usage
      print('Remaining requests', odds_response.headers['x-requests-remaining'])
      print('Used requests', odds_response.headers['x-requests-used'])

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$odds'):
        odds = get_odds()
        await message.channel.send(odds)

client.run(os.getenv('TOKEN'))

A: The odds response object contains a list of events. You're currently only returning the first one with return(odds_json['data'][0]). (The index 0 is giving you just the first element of the list.)
If you wanted to print all of the teams, you could loop over the events and get each matchup like this:
for event in odds_json['data']:
    print(event["teams"])


text:
Q: Mulesoft XML Accessing Schema Documentation I'm trying to build mule 4 XML file validation. In order to do that i'm trying to access the xsd file for the Database connector using the following link: http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd. But I'm getting 502 (Bad Gateway) error.
May I know how do we access this XSD file? Is there somewhere we have to register ourselves or something?

A: The XSD files for Mule Runtime and Mule connectors are inside the jars of the plugin, not published in the web. There is no documented way to do this.


text:
Q: Python - How to get the first row of each list? I need to get each row of a list and make a new list. Let me explain.
I have this:
data = [[204.0, u'stock'], [204.0, u'stock']]

I need to transform in this:
column1 = [204.0, 204.0]
colunm2 = [u'stock', u'stock']

Any clues on how can this be done?
Best Regards,

A: Use zip():
>>> data = [[204.0, u'stock'], [204.0, u'stock']]
>>> zip(*data)
[(204.0, 204.0), (u'stock', u'stock')]
>>> column1, column2 = zip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')

Or, izip() from itertools:
>>> from itertools import izip
>>> column1, column2 = izip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')

A: A simple list comprehension will do the trick.
data = [[204.0, u'stock'], [204.0, u'stock']]

column1 = [i[0] for i in data]
column2 = [i[1] for i in data]

>>> column1
 [204.0, 204.0]
>>> column2
 ['stock', 'stock']

A: may be , in one line
>>> data = [[204.0, u'stock'], [204.0, u'stock']]
>>> columns = [ [d[k] for d in data] for k in range(2)]
[[204.0, 204.0], ['stock', 'stock']]
>>> columns[0]
[204.0, 204.0]

and if the size of variable can change you can do this :
columns = [ [d[k] for d in data] for k in range(max(map(len,data)))]


text:
Q: Unable to import babel-plugins/presets in production for transform I am using babel in production to transform jsx strings into html, for the purpose of rendering email bodies via string templates.
import {transform} from '@babel/core';
const {code} = transform(template, {plugins: ['@babel/plugin-transform-react-jsx']});

I have @babel/core and @babel/plugin-transform-react-jsx in my dependencies. The code works on development but on production it fails saying, 'Can not find module @babel/plugin-transform-react-jsx'. Can someone help me debug/understand the underlying issue here?
I tried adding a deliberate import '@babel/plugin-transform-react-jsx'; but to no avail.
Sample code for the same: https://codesandbox.io/s/cool-euler-v21z3
Can it be a deployment issue? The complete error logs:
Exception while invoking method 'template.getComponentFunctions' Error: Cannot find module '@babel/plugin-transform-react-jsx' from '/built_app/programs/server'
[13.127.129.224]    at Function.module.exports [as sync] (/built_app/programs/server/npm/node_modules/resolve/lib/sync.js:58:15)
[13.127.129.224]    at resolveStandardizedName (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/files/plugins.js:101:31)
[13.127.129.224]    at resolvePlugin (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/files/plugins.js:54:10)
[13.127.129.224]    at loadPlugin (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/files/plugins.js:62:20)
[13.127.129.224]    at createDescriptor (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
[13.127.129.224]    at /built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:109:50
[13.127.129.224]    at Array.map (<anonymous>)
[13.127.129.224]    at createDescriptors (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
[13.127.129.224]    at createPluginDescriptors (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:105:10)
[13.127.129.224]    at /built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:63:53
[13.127.129.224]    at cachedFunction (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/caching.js:62:27)
[13.127.129.224]    at cachedFunction.next (<anonymous>)
[13.127.129.224]    at evaluateSync (/built_app/programs/server/npm/node_modules/gensync/index.js:244:28)
[13.127.129.224]    at sync (/built_app/programs/server/npm/node_modules/gensync/index.js:84:14)
[13.127.129.224]    at plugins (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-descriptors.js:28:77)
[13.127.129.224]    at mergeChainOpts (/built_app/programs/server/npm/node_modules/@babel/core/lib/config/config-chain.js:319:26)

A: While I was unable to figure out the reason and solve it properly, I was able to work around by using @babel/standalone.


text:
Q: Laravel graceful end event-listener within a request Within my controller I am creating a message which then fires an event after a successful message create:
public function store(Conversation $conversation, Request $request)
{
    $message = Message::create(...)

    event(new MessageCreated($message));

    return response([
        'message' => $message,
    ]);
}

Now the event has a few listeners on it, one of which checks if it can send a message over external provider. What I am doing within a listener is throwing an error if something fails.
I don't understand how could an exception trace of a listener come as a response to POST /message request since I am returning right after an event. Following on that, I would like to return a custom response if something fails so I can fail gracefully, and surely enough this works:
try {
    event(new MessageCreated($message));
} catch (\Exception $e) {
    return 'failed';
}

But...why does it work? It seems very wrong. Is there a more standard way to handle this?

A: By your code I assume this is not an queued event. In that case the execution on this event is not async but sync.
By that I mean that execution goes all the was to your
event(new MessageCreated($message));
then "summons" (so to speak) a piece of code (in your case MessageCreated($message)) which then throws an exception. However that exception is caught in your handler (App\Exceptions\Handler) and returned as a 500 server error.
You can catch those exceptions there and ignore them or you can go with what is written in the docs https://laravel.com/docs/7.x/events#defining-listeners
Stopping The Propagation Of An Event

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.


text:
Q: How can I set the starting folder for new shells using gnome-terminal when launching from xfe? I like to use xfe because it's quick and I make use of the 3 panes. I'm using ubuntu and I like using gnome-terminal but I can't get xfe to launch gnome-terminal with the bash shell in the same folder as the xfe pane.
In xfe, if you press ctrl-t it'll open xterm (by default) in the current folder. I'd like that to happen in gnome-terminal instead. Sometimes I get errors, sometimes it just doesn't put me into the desired folder.
I've tried a few things

*

*using parameters with the -- and the -x (which tells me is deprecated in favor of --).

*I've created a script and tried cd $@ and $@ in various forms surrounded by double quotes and not

*Used a script to populate the --working-directory= surrounded by quotes and not

It works rather seamlessly without a lot of effort for xfce4-terminal, and I may just switch to that over xterm, but I'd still like to get it to work with gnome-terminal.
I think there's some confusion about "working directory"... i'm actually looking for bash to start in that directory once the terminal program opens, not necessarily that the terminal program itself starts in or uses the "working directory".
Ultimately, I want the output of pwd in a new terminal from xfe to be equal to the path of the selected pane in xfe. Call it whatever you want. The above are just some things that I tried.


text:
Q: How to search for value in all descendant textNodes(Javascript)? So basically I am making a Chrome extension which sorts the search results on Ebay by their popularity(number of times sold). To do this I need to find all li elements which have a descendant text node containing the text ...+ Sold where ... is a number.
Basically, search results on Ebay look like this:

62+ Sold

In every li element I have to search for the text Sold and extract the number out of that text node to process it further. How can I do that?

A: Use a selector string: select li.s-item span to select all spans which descend from an li with a class of s-item, check to see if the span's only child is a text node with "Sold" in it, and if so, do whatever you need to do with it.
If you're sure that any
 will do, and not just those with a class of s-item, then use 'li span' instead:

document.querySelectorAll('li span').forEach(({ childNodes, textContent }) => {
  if (childNodes.length !== 1 || childNodes[0].nodeType !== 3 || !textContent.includes('Sold')) return;
  const count = textContent.match(/\d+/);
  console.log('Processing span with sold number ' + count);
});

62+ Sold

333+ Sold

A: You cannot do that only by using childNodes or children properties because they return only the children and not all descendants of the current node. So you will have to write your own function for that, something like:
function getDescendants(node, arr) {
      var i;
      arr = arr || [];
      for (i = 0; i < node.childNodes.length; i++) {
          arr.push(node.childNodes[i])
          getDescendants(node.childNodes[i], arr);
      }
      return arr;
  }

Using this function, you just simply iterate over all descendants and check if they are text nodes ( nodeType == 3 ) and after that search for the word Sold in them. Extracting the number is pretty easy after that.
Something like:
var searchValue = "Sold";
var descendants = getDescendants(listItem);
for(var j = 0; j < descendants.length; j++) {
    if(descendants[j].nodeType == 3){
        if(descendants[j].nodeValue.indexOf(searchValue) > -1){
            var text = descendants[j].nodeValue.trim();
            //"37+ Sold"    for example
            var soldNr = text.substring(0, text.indexOf(searchValue)-2);
            //you process your number(soldNr) further
        }
    }
}


text:
Q: Cordova/Angular/Ionic iOS App stops working after date change (Javascript) I have an issue when executing an hybrid app and then accessing to Settings > General > Date & Time (App now is in background), I proceed to set up a date previous than the current one, after that, Javascript doesn't seem to work: I press buttons that should trigger functions defined to my Angular controller and don't seem to work.
After setting up the current day, the app starts working correctly.
This issue was tested on an iPhone 5 running iOS 7.1.1
Apache Cordova: 4.2.0
AngularJS: 1.3
Ionic: 1.3.11
Any help would be greatly appreciated.
Thanks in advance.


text:
Q: Negamax for simple addition game I'm trying to implement negamax for a simple game where the players alternate adding one or two to a running sum. The player that increases the total to 21 wins.
I'm using the pseudocode here: https://en.wikipedia.org/wiki/Negamax#Negamax_base_algorithm
The human player moves first so the computer should easily win by adding the number that makes the total congruent to 0 mod 3.
I'm not doing any dynamic move generation. Just comparing the negamax score for adding 1 to the running sum to the negamax score for adding 2 to the running sum.
int total = 0;

Console.WriteLine("the current total is " + total);

while (total < 21) {
    Console.WriteLine("add 1 or 2?");
    total += Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("you increased the total to " + total);
    if (total == 21) {
        Console.WriteLine("you win");
        break;
    }

    if (negamax(total + 1, 1) > negamax(total + 2, 1)) total++;
    else total += 2;

    Console.WriteLine("computer increased the total to " + total);
    if (total == 21) {
        Console.WriteLine("computer wins");
        break;
    }
}

The negamax function:
static int negamax(int total, int color) {
    if (total == 21) {
        return color * 100;
    }

    int bestValue = -100;

    for (int i = 1; i <= 2; i++) {
        if (total + i <= 21) {
            int v = -1 * negamax(total + i, -1 * color);
            bestValue = max(bestValue, v);
        }
    }
    return bestValue;
}

Max Method:
static int max(int a, int b) {
    if (a > b) return a;
    return b;
}

Not sure why the AI is just adding 2 every time.

A: The static evaluation function is incorrect.
https://en.wikipedia.org/wiki/Negamax#Negamax_base_algorithm
The negamax node's return value is a heuristic score from the point of view of the node's current player.
if (total == 21), it's always a loss for the node's current player. So negamax return must be -100. There are other code errors too, such as when total is 22.

A: A player who cannot make a move obviously loses the game, right?
If so, then
if (total == 21) {
    return color * 100;
}

looks wrong to me, because it inverts the rules. You are saying that the player who cannot make move wins! Try to rework these 3 lines.


text:
Q: Angular: Correct way to define custom type/model for object that can contain many different properties? My goal is to use TypeScript to enhance the readability of my current code base. I've realized in many Services & Components I am ending up with a lot of code that has parameters types and return types of any.
For example something like the code below, but with many more functions.
import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

  private someFuncA(objA: any): void {
    // Do some work
  }
  private someFunB(objA: any): any {
    // Do some work
  }
  private someFunC(objB: any): string {
    // Do some work
  }
}

The problem is objA is a really large object that can have hundreds of properties. Sometimes those properties are present and sometimes they are not. The objects are coming from the Server and I do not have the ability to change them.
What I would like to do is change the any types to something meaningful so the code is more easily read. For example like the following code:
import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

  private someFuncA(objA: SeismicData): void {
    // Do some work
  }
  private someFunB(objA: SeismicData): SeismicData {
    // Do some work
  }
  private someFunC(objB: ReflectiveData): number {
    // Do some work
  }
}

I know I can't use any interface, because the structure of the objects are so dynamic. Properties can exist in one instance and not in another. I am not sure if it makes sense to create a model that is just blank for example:
export class SeismicData {}

However, I do not feel that is the best/correct practice and hope that someone in the community can guide me in the right direction on how to handle a use case like this.

A: While the type that your function returns is very important and you should use it when possible, I don't think you have to create classes just for specific types of data that can return results of type any.
It's not a problem if a class contains several functions and properties, what matters most are the concepts of cohesion and coupling. If you know your functions are relevant to the objective of the class itself, and you think that each method is unique enough to justify being on its own and not adding as part of another function, you are writing your code properly. That being said, if you want to improve readability, make the names of your variables as unique as you can,and leave comments in places where there might be confusion, and if you have to return an any type, then you have to.
Might've gone on a tangent, but hope this helped.

A: If there is some set of standard properties and the issue is that some exist in some instances and others don't, then you can still use an interface:
For example:
export interface Movie {
    id: number | null;
    approvalRating?: number | null;
    description?: string;
    director?: string;
    imageurl?: string;
    mpaa?: string;
    price?: number | null;
    releaseDate?: string;
    starRating?: number | null;
    title?: string;
    category?: string;
    tags?: string[];
}

The question marks imply that the properties are optional. So in the above example the only required property is the id.
This would only make sense if there is some predefined set of properties for your object, but only some of them are present.
If you really have no idea what properties you'll get, then an interface does not make sense.


text:
Q: nested mail merge options I need to perform an automated mail merge using .net driven from an asp.net front end.
The mail merge needs to support nested fields, I have come across a product form Aspose but it's highly unlikely that my company would purchase it given its price.
Are there any other alternative options that support nested data in a way or similar to the aspose product?

A: Not sure what exactly do you mean with "nested" fields. But.. may be this could be helpful, and it's free. It's called NTemplates and it's free and open source. It's hosted at codeplex.com: www.ntemplates.codeplex.com


text:
Q: Regex for remove everything after | (with | ) I was trying to find a solution for my problem.
Input:
This is the sample title | mypcworld

Output:
This is the sample title

I want to remove everything comes after " | " using simple regex on notepad++
It seems to be really simple one. But I was tried with some other regex "|.*$" listed on here, but no luck. The problem was the character "|" was alteration equivalent of or.
So please help me to solve it.

A: In a .txt file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+ in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button

A: If you want to get everything after | excluding set character use this code.
[^|]*$

Others solutions \|.*$
Results : | mypcworld

This one [^|]*$
Results : mypcworld

http://regexr.com/3elkd

A: The pipe, |, is a special-character in regex (meaning "or") and you'll have to escape it with a \.
Using your current regex:
\|.*$

I've tried this in Notepad++, as you've mentioned, and it appears to work well.


text:
Q: jQuery and .Net CRUD searching I've got the problem with my jQuery function to search the elements from the list that are matching the entered string. It's always showing that no data was found.
I've tried with various modifications, but nothing helped.
Here is the code for jQuery function
      $(document).ready(function () {
    $("#SearchBtn").click(function () {
        console.log("ttt");
        var SearchBy = $("#SearchBy").val();
        var SearchValue = $("#Search").val();
        var SetData = $("#SetStudentList");
        SetData.html("");
        $.ajax({
            type: "post",
            url: "/Home/GetSearchingData?SearchBy=" + SearchBy + "&SearchValue=" + SearchValue,
            contentType: "html",
            success: function (result) {
                if (result.length == 0) {
                    SetData.append('
No Match Data
')
                }
                else {
                    $.each(result, function (index, value) {
                        var Data = "
" +
                            "" + StudentList[i].StudentId + "	" +
                            "" + StudentList[i].StudentName + "	" +
                            "" + StudentList[i].Email + "	" +
                            "" + StudentList[i].DepartmentName + "	" +
                            "" + "" + "	" +
                            "" + "" + "	" +
                            "
";
                        SetData.append(Data);

                    });
                }
            }

        });
    });

});

Html for search button:
          Search By :
    <select id="SearchBy">
        <option value="StudentID">Student ID</option>
        <option value="StudentName">Student Name</option>
        <option value="Email">Email</option>
        <option value="Department">Department</option>
    </select>

    @Html.TextBox("Search")<input type="submit" id="SearchBtn" value="Search" />

Methods from controller (searching and also getlist and getbyID, as i was even trying to call getlist after search button is clicked, but always there was info 'no matching results'):
    public JsonResult GetSearchingData (string SearchBy, string SearchValue)
    {
        List<StudentViewModel> StuList = new List<StudentViewModel>();
        if (SearchBy == "Student ID")
        {
            try
            {
                int Id = Convert.ToInt32(SearchValue);
                StuList = db.tblStudent.Where(x => x.StudentId == Id || SearchValue == null).Select(x => new StudentViewModel
                {
                    StudentId = x.StudentId,
                    StudentName = x.StudentName,
                    Email = x.Email,
                    DepartmentName = x.tblDepartment.DepartmentName
                }).ToList();

            }
            catch (FormatException)
            {
                Console.WriteLine("{0} Is Not A ID ", SearchValue);
            }
            return Json(StuList, JsonRequestBehavior.AllowGet);
        }
        else
        {
            StuList = db.tblStudent.Where(x=>x.StudentName.Contains(SearchValue) || SearchValue == null).Select(x => new StudentViewModel
            {
                StudentId = x.StudentId,
                StudentName = x.StudentName,
                Email = x.Email,
                DepartmentName = x.tblDepartment.DepartmentName
            }).ToList();
            return Json(StuList, JsonRequestBehavior.AllowGet);
        }
    }

         public JsonResult GetStudentList()
    {
        List<StudentViewModel> StuList = db.tblStudent.Where(x => x.IsDeleted == false).Select(x => new StudentViewModel
        {
            StudentId = x.StudentId,
            StudentName = x.StudentName,
            Email = x.Email,
            DepartmentName = x.tblDepartment.DepartmentName
        }).ToList();

        return Json(StuList, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetStudentById (int StudentId)
    {
        tblStudent model = db.tblStudent.Where(x => x.StudentId == StudentId).SingleOrDefault();
        string value = string.Empty;
        value = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        });
        return Json(value, JsonRequestBehavior.AllowGet);
    }

Any help would be much appreciated.


text:
Q: Custom Sinatra route I'm looking to make a custom route for my Sinatra blog project which shows the user the last entered post in the database.
get "/most-recent-job" do
  Job.last

Can anyone help? I can't find info in my curriculum for such a request.

A: The Sinatra documentation on routes is pretty thorough. Assuming you're just trying to call a class method of Jobs::last, and that the method returns something stringifyable, then:
get '/most-recent-job' do
  Jobs.last
end

should get it done. If that's insufficient for your use case, you'll have to expand your question to include code and output showing what Jobs.last is supposed to return, whatever errors you're getting from the route currently, and what you think the route's output ought to look like if you're expecting a MIME type other than text/plain.


text:
Q: JSP - File Uploading Tutorials for File Uploading. I copied the code and saved it my project. I change the
String filePath = context.getInitParameter("file-upload");

into
String filePath = context.getInitParameter("uploads");

Because I want to save the image in the folder named uploads. This folder is located outside the folder where I have put the script. I even tried
String filePath = context.getInitParameter("../uploads");

But in the output code
out.println("Uploaded Filename: " + filePath + fileName + "<br>");

FilePath is null and there is no image in the folder. How to properly set the filePath?

A:
String filePath = context.getInitParameter("file-upload")

you are getting the value from  web.xml, If you want to store in dirrefernt location change the file path in web.xml as follows
<param-value>
    c:\apache-tomcat-5.5.29\webapps\data\uploads
</param-value>

A: The init parameter comes from the web.xml.
There you will have to declare for that servlet an init parameter named uploads with a value of your destination.
Please study some doc's about servlets or webapps.
Sorry for this short answer but it seems there is some basic knowledge about servlets missing here so digging into some more tutorials and doc's makes more sense than trying here to explain some fundamentals. ;-)

A: You can store directory details in properties file as well--
in catalina.properties store values like below(this file is located at $CATALINA_HOME/conf/catalina.properties)
my.home=directory/path

(WEB-INF/web.xml)
<context-param>
<param-name>uploads</param-name>
<param-value>${my.home}</param-value>
</context-param>

and then try
String filePath = context.getInitParameter("uploads");


text:
Q: Database Sync Problem The software my company puts on each of our customers' mobile computers has a local MySQL database. These mobile computers are connected to the internet via a mobile broadband card. We send information to be read into a string and stored in the customer's local database via XML files which range from 1kb to 600kb. (Note: We do this so customers will still have access to the data when an internet connection is unavailable.)
The 1-600kb XML files are stored in a folder for each user on our server until they are downloaded via a .net/C# webservice which serves up the file to the client which calls on the webservice with their token. Customers may have up to 20-40mb of these small XML files when they connect for the first time. In a normal day, they may download up to a few mb of these files. The software on the customer's mobile computer checks for files in their folder on the server every 10 seconds with a webservice.
A new XML file is made every 15 minutes with the changes which need to be made to the user's database, and no XML file is created if no changes are made. The largest XML file (600kb) has 1000 records for the user's local database. Each record has 10+ columns some with 10+ characters.
The problems with our method:

*

*This method is slow. (It can take 1 1/2 hours to get an empty database in sync.)

*There is no compression to the XML files, so download sizes are larger than necessary.

*The XML files are larger than they need to be because they contain unnecessary information.

*We are not keeping track of what's in the user's database, so users can become out of sync.

*It's file based, and this is causes lots of reads/writes on the hard disk.
Can anyone suggest a better way to do this?

A: Sounds like two problems to me.

*

*Updating the user databases to the latest master database can be done by keeping track of versions. The user submits their version number when they call, and you return the SQL needed to update their version to the latest. Each time you update the master database, generate SQL to update from each possible previous version, then just return the appropriate SQL. I say SQL because that seems more efficient, but you can use XML or JSON or whatever and it would still be more efficient with versions.

*Respecting user local changes is a more challenging problem. You could save the user changes as SQL or some other format off to the side, and re-apply them after the update. But who has the latest/best info is a difficult question. Often you need greater granularity than just user records. It's possible for one system to update part of the info - say a phone number for a contact - while the other system updates another part, say their email. If the system has to choose one contact entry or the other, either way you loose. To get it right you have to timestamp the changes to every field. If the remote devices are always online, you may have better luck attempting a sync and asking the user to resolve conflicts each time they want to make a change.


text:
Q: Create custom numbering in Postgres I have a table that includes these columns:
track    track_id
-----------------
1        1
1        1
0        2
1        2
1        2
0        3
1        3
1        3
0        4
0        5
....

I have the column track and want to calculate track_id, which would be:
Starting by 1, every time track is 0, track_id should be incremented by 1 (0 specifies the beginning of a new track).
I wish I could set a variable and then increment it every time the condition is true, but there does't seem to be a simple way to do that.
I would appreciate a query that can pull this. Thank you.

A: First, you need a column that specifies the ordering.  SQL tables represent unordered sets.  Let me assume you have such a column, which I'll just call id.
Then, you can use a cumulative sum:
select t.*, 1 + sum( (track = 0)::int ) over (order by id) as track_id
from t;

If track only takes on the values 0 and 1, you can simplify this even more:
select t.*, 1 + sum(1 - track) over (order by id) as track_id
from t;


text:
Q: Accessing Service Data from Directive I am trying to show or hide the HTML elements based on spring security roles using Angular JS.
For this, I have created a service and directive.
I am getting data back from the server but I am not able to access the data that I got in service. Here is my code
    app.service('MyService', function($http, $rootScope) {
    this.data = [];
    var _this = this;

    $http.get('permissions').then(function data(response) {
        _this.data=response.data;
        console.log(response);
        $rootScope.$broadcast('MyServiceReady');
    })

/*  return  {
        permissionData: function(){
            return _this.data;
        }
    }*/
})

app.directive('allowed', [ 'MyService', function(MyService) {
    return function(scope, element, attr) {
        scope.$on('MyServiceReady', function() {

            $subScope = this;

            $subScope.status = false;
            $subScope.permissions=MyService.data;
            console.log(MyService.data);
            console.log("First:" + $subScope.status+" permission:"+attr.allowed);
            angular.forEach(permissions, function(item) {

                if (angular.equals(item, attr.allowed)) {

                    $subScope.status = true;

                }

            });

            console.log("last:" + $subScope.status);
            console.log(element);
            if (!$subScope.status) {
                $(element).hide();
            } else {
                $(element).show();
            }

        });
    };
} ]);

I tried to write a function inside the service and access it but even then it is showing MyService.permissionData is not a function.
Can anyone explain where I am going wrong?
I am trying to perform three tasks in the above code.

*

*Get the Permissions array from the server

*Dont create the directive till you get data.

*hide or show elements based on permission.
My HTML code for this is:
    <button class="btn btn-primary" allowed="1002">ADD SOMETHING</button>

Please do reply if you got any suggestions.

A: Try removing MyService from these two lines:
return function(scope, element, attr, MyService) {
    scope.$on('MyServiceReady', function(MyService) {

You've already injected MyService into your directive, you don't pass it on the link function or your event handler.
Now that you've fleshed out what it is you're trying to do in your question I think I have a better answer for you to look at. If I'm reading this right, you are getting an array of integers that correspond to the allowed attribute on your buttons. If the array doesn't contain the value in allowed then the button should not be visible.
Here is a new version of your directive:
.directive('allowed', function(MyService) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$on('MyServiceReady', function() {
                var allowed = false;
                angular.forEach(MyService.data, function(item) {
                    if(attrs.allowed === item){
                        allowed = true;
                    }
                });
                if(!allowed){
                    element.addClass('hidden');
                }
            });
        }
    }
})

This requires a hidden class in your CSS with display: none;. Here's a working JSFiddle to illustrate the directive. I had to fake the $http call to your API. A downside to this approach is that the buttons are visible while the service is calling your API. It might be better to hide them by default and then show them if the user is allowed instead of vice versa.


text:
Q: A word for "interesting feature" I am searching for a good english word that would be an analogy for russian word izuminka, direct translation is raisin, but it is used in figurative sense.
Other synonyms I've found: appeal, picanthy, zest.
Most close meaning would be an interesting feature.
So it is something that makes the object not so common
and this single feature tends to add an improvement, mostly when speaking about visual appeal or taste.
E.g.: "She is not exactly an attractive woman, but she has an ... "
Also it should be possible to use the same word in ironical sense,
so if put in quotes it becomes a mockery:
For example a new website or software feature:

A: What is this new annoying feature?
  B: You don't get it, this is a "..."

Or nitpicking about someone's look:

A: Why does she wear these ugly yellow shoes?
  B: It is sort of her "..."

A: The rather vague term, something is often used that way

A remarkable or important thing or person: He thinks he is something in that uniform.

American Heritage
In your case, you could say

She is not exactly an attractive woman, but she has something.

It is often said with a slightly rising inflection that suggests the feature is difficult to quite grasp or express. It is related to the French phrase (often used in English), je ne sais quoi.
A related term is a certain something, as in

She is not exactly an attractive woman, but she has a certain something.

Related Phrases are something else and really (quite) something
Oxford Dictionaries Online
It also can be used in a slightly derrogatory manner, ususally connoted by tone.

He is really something. [The emphasis would be on really, drawn out with an ascending tone].

See, also, the lyrics of the Beatles tune, Something

A: je ne sais quoi, defined by The Cambridge English Dictionary as

French for 'I don't know what': a pleasing quality that cannot be
  exactly named or described:
Although he's not conventionally attractive, he has a certain je ne
  sais quoi that makes him popular with the ladies.

This term fits the OP's three examples very well.
Complimentary:

She is not exactly an attractive woman, but she has a certain je ne
  sais quoi.

Ironic and mocking:

A: What is this new annoying feature?
B: You don't get it, this is a "je ne sais quoi"!

Nitpicking (with a few additions to B's response):

A: Why does she wear these ugly yellow shoes?
B: (with a shrug): It is sort of her...aah..."je ne sais quoi".

True, it is a French phrase, but widely used in English, and in an English dictionary.

A:
"Quirk"   N. https://en.oxforddictionaries.com/definition/quirk
1 A peculiar aspect of a person's character or behaviour:
'they accepted her attitude as one of her little quirks
'Every commander also has pet peeves, quirks, and peculiarities.
''He rightly concentrates on the particular textures and quirks of the
characters rather than on the scenery.'

It isnt a perfect fit as it signifies more that which makes something unique rather than better, but it fits your examples quite well.

"Feature"
N.
https://en.oxforddictionaries.com/definition/feature
1A distinctive attribute or aspect of something:
'a well-appointed house with interesting decorative features'
'one salient feature of the case has been overlooked'

However, this skips the sense of a feature as a positive feature, such as used in marketing and software.
https://en.m.wikipedia.org/wiki/Undocumented_feature
http://www.infoworld.com/article/2626052/tech-support/it-s-not-a-bug--it-s-a-feature----and-you-ll-pay-either-way.html
(Couldn't find a particularly good link to the phrase "It's not a bug, it's a feature", but that's because it's so very common.)
Anyhow, the sense as a positive feature is pretty normal, albeit not exclusive.


text:
Q: How to handle System.OverflowException I have one simple windows application in that amount Textbox is there. When i enter amount into amount textbox it will convert it to words in another textbox named txtrupees. Amount Textbox field maximum length is set to 11 places in that last 3 places .00.
My problem is now when i Enter amount with .00 it is working fine. But if i enter 11 places it will giving following Error:

System.OverflowException' occurred in mscorlib.dll Value was either too large or too small for an Int32.tried following code.

How can I prevent this kind of error?
private void txtamount_TextChanged(object sender, EventArgs e)
{
    if (txtamount.Text != string.Empty)
    {
        string[] amount = txtamount.Text.Split('.');
        if (amount.Length == 2)
        {
            int rs, ps;
            int.TryParse(amount[0], out rs);
            int.TryParse(amount[1], out ps);

            string rupees = words(rs);
            string paises = words(ps);
            txtrupees.Text = rupees + " rupees and " + paises + " paisa only ";
        }
        else if (amount.Length == 1)
        {
            string rupees = words(Convert.ToInt32(amount[0]));
            txtrupees.Text = rupees + " rupees only";
        }
    }
}

A: The issue comes from Convert.ToInt32(amount[0]) where amount[0] can be almost anything, including being superior to Int.MaxValue or inferior to Int.MinValue which would cause an overflow.
Use int.TryParse(amount[0], out foo); and use foo:
else if (amount.Length == 1)
{
    int ps;
    if(int.TryParse(amount[0], out ps))
    {
        string rupees = words(ps);
        txtrupees.Text = rupees + " rupees only";
    }
    else
        txtrupees.Text = "Invalid number";
}

If you want to deal with bigger numbers, you can use Int64, Double or Decimal

A: a number that has 11 places is larger than a Int32 number. I suggest you should use int64 instead of int32
https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx


text:
Q: How to Concat Datetime without Losing Second Precision What is best way to Concat on datetime column with other fields, without losing/truncate millisecond precision?
Example: We have a column in datetime precision.
1988-02-27 00:00:04.000

We are creating rowhash on CONCAT
select hashbytes('SHA2_256',concat(SalesRecord,SalesDatetime))

The problem when doing Concat, we are losing second values.
You can test here,
create table dbo.SalesOrder
(
    SalesOrderId int primary key,
    SalesRecord varchar(255),
    SalesDatetime datetime
)
select concat(SalesRecord,SalesDateTime) from dbo.SalesOrder
select concat('ABC ',[SalesDateTime]) from dbo.SalesOrder

ABC Feb 27 1988 12:00AM

What is the optimal way to solve this?
Background: Rowhash was causing duplicates by removing seconds, pipe deliminator | not working either.
The following was not working:
declare @testdate datetime = '1988-02-27 00:00:04.000'
select concat('ABC',convert(binary(16),@testdate))
select concat('ABC',convert(varchar(25),@testdate))

A: You are losing seconds because the default format for converting datetime to string is the same as:
SELECT CONVERT(char(19), GETDATE(), 0);

Which outputs (for me, right now):
Oct 30 2018  2:02PM

You can try something more like this:
SELECT CONCAT
       (
         'ABC ',
         CONVERT(char(19), GETDATE(), 25)
       );

Which outputs (again, for me, right now):
ABC 2018-10-30 14:02:55

If second aren't enough, just change char(19) to char(23). If that's still not enough, you can consider changing that column to datetime2 to get more precision.

A: Try converting the DATETIME value to a DATETIME2(3) before concatenating.
DECLARE @now DATETIME = GETDATE();

SELECT
    CONCAT('ABC ', @now),
    CONCAT('ABC ', CONVERT(DATETIME2(3), @now));

Results:
ABC Oct 30 2018  3:01PM                      ABC 2018-10-30 15:01:30.617


text:
Q: IPv6: Why ping to another IPv6 host doesn't work when loopback interface is DOWN While it is said the only job of lo interface is to test its own connectivity, why doesn't pinging another IPv6 host work when the lo interface is made DOWN.
Network configuration:

*

*host1(eth0) - 1001::1/64

*host2(eth0) - 1001::2/64

Steps:

*

*Ping from Host1 to 1001::2; works fine.

*Make lo interface DOWN on host1.

*Ping from Host1 to 1001::2; doesn't work.

Additional Info:
Debian 3.16.x
root@suprman# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever

root@suprman# ifconfig lo down

root@suprman# ip a
1: lo: <LOOPBACK> mtu 65536 qdisc noqueue state DOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever


text:
Q: How to implement a "render-to-texture" pipeline in Direct3D 11? I am trying to some GPGPU calculations using HLSL and Direct3D 11.
My goal is to calculate several images sequentially (one rendering per image), then sum them.
To achive this I created three textures: one is an input, two are for summarizing the results. The method I am trying: first I render to texture2 (and I use the texture and texture3 textures as input), then I render to texture3 with a slightly modified pixel shader (and I use the texture and texture2 textures as input). After this, I dump the textures to a PNG file. My problem is that somehow the second pixel shader doesn't get the result of the first shader (texture2), but the original, empty texture. I defined both texture, texture2, and texture3 with usage D3D11_USAGE_DEFAULT, and D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE binding flags.
My HLSL shader (shader1):
float4 main(PS_INPUT input) : SV_TARGET
{
...
float4 val5 = 0.25F * (val + val2 + val3 + val4) + tex3.Sample(sam, input.Tex4);
return val5;
}

The other shader (shader2):
float4 main(PS_INPUT input) : SV_TARGET
{
...
float4 val5 = 0.25F * (val + val2 + val3 + val4) + tex2.Sample(sam, input.Tex4);
return val5;
}

The code that performns the rendering and the dumping of textures:
context->OMSetRenderTargets(1, &targetViewTexture2, NULL);

float z = 280.0F;
GenMatrix(z);
context->VSSetShader(vs, NULL, 0);
context->PSSetShader(ps, NULL, 0);
context->PSSetSamplers(0, 1, &state);
context->VSSetConstantBuffers(0, 1, &cbuf);
context->Draw(6, 0);
swapChain->Present(0, 0);

context->OMSetRenderTargets(1, &targetViewTexture3, NULL);
z = 0.0F;
GenMatrix(z);
context->VSSetShader(vs, NULL, 0);
context->PSSetShader(ps2, NULL, 0);
context->PSSetSamplers(0, 1, &state);
context->VSSetConstantBuffers(0, 1, &cbuf);
context->Draw(6, 0);
swapChain->Present(0, 0);
DirectX::ScratchImage im;
DirectX::CaptureTexture(device, context, texture3, im);
const DirectX::Image *realImage = im.GetImage(0, 0, 0);
HRESULT hr2 = DirectX::SaveToWICFile(*realImage, DirectX::WIC_FLAGS_NONE, GUID_ContainerFormatPng, L"output_tex3.png", NULL);
DirectX::CaptureTexture(device, context, texture2, im);
realImage = im.GetImage(0, 0, 0);
hr2 = DirectX::SaveToWICFile(*realImage, DirectX::WIC_FLAGS_NONE, GUID_ContainerFormatPng, L"output_tex2.png", NULL);

The ouput of the first pass (ps) is correct, but the second is not. If I only leave the shader code:
    float4 val5 = tex2.Sample(sam, input.Tex4);

I get an empty image. Am I missing something? Do I have to call some methods to use the texture in the second pixel shader? I think I pinpointed the relevant sections of my large code base, but if you need more information just ask for it in the comment section.

A: The problem was that I used the texture both as input and output. You could use a texture either as input or render target in one pass.


text:
Q: Swagger UI input set of variables I create an swagger API as below

However, I am blocked to input set of UUID through swagger UI without any reason. It seems that I don't input in correct format (""","" or ["",""] )

May I know how to input correct set of UUID or other suggestion?
Thanks.