text:
Q: uploading text file from C# to IBM MVS I'm trying to upload a text file (converted to ebcdic) into a library in MVS using C#.  For uploading a file, I used the following string: filename = @"ftp://xx.xx.xx.xx//'myFile'"; It is not possible without the apostrophes.
Now, I used @"ftp://xx.xx.xx.xx//'libary_name(myFile)'" for upload into a library but I get incorrect syntax or parameters error.  Library name: user_id.xyz.temp_lib and myFile: user_id.xyz.someFile. How do I go about fixing this?
Also, is there a way to control the block size of the text file in c#? MVS currently states the uploaded file as VB but I want it as FB (length specified of course).
Thanks

A: Two thoughts...
Your first example suggests a basic misunderstanding of MVS file names.
Unlike Unix, DOS or MS Windows there is no such thing as a folder or "path".  The entire MVS file is defined in the system catalog by its unique dataset name which can not exceed 44 characters.  The file can vary in organizational structure which may or may not have an internal directory or index.  It can be a simple flat file, or a PDS, or VSAM, or GDG, or database etc. You have to understand what type of file you are working with to use it correctly.
In this situation, you called it a "library" and you further indicated this library has a member name which strongly hints that the file is organized as a PDS dataset.  As a PDS, there is an internal directory and you can have multiple members, but no single member name may exceed 8 bytes.  The member name counts toward the 44 byte name space limitation of the file name.  As Erf indicated, the PDS member name is limited to letters, numbers and a few national characters.  The data within the member is accessed sequentially.
In your first example you indicated the member name is:  user_id.xyz.someFile
That name is obviously invalid as it exceeds the 8 byte limit.  If you had shortend the name your example may have worked.  Indeed, it appears in your corrected example that you fixed the illegal member name issue by creating a PDS member called "someFile" and that is pefectly valid.
2nd thought...
You said "If you use the full MVS data set path on this command, you will get an error."
That statement sounds incorrect and indicates you may not have allowed for the fact that the FTP session is appending the user id to your file name automatically.  While allowing FTP to default your file name works fine, in most cases you should explicitly qualify the entire MVS file name.
Without the apostrophes, FTP should append your user id to the MVS file name by default. The following names are equivalent...
@"ftp://xx.xx.xx.xx//libary_name(aMember)"
@"ftp://xx.xx.xx.xx//'user_id.libary_name(aMember)'"

With the apostrophes, FTP expects you to explicitly name the fully-qualified MVS file name.  It will not append the user id for you.
This example shows the difference:
@"ftp://xx.xx.xx.xx//libary_name(aMember)"        <- user_id.libary_name(aMember)
@"ftp://xx.xx.xx.xx//'xyz.libary_name(aMember)'"  <- xyz.libary_name(aMember)

You mentioned that FTP will not work without apostrophes.  That surprises me.  Have you tried using the C# escape double-quote (\") character instead?  I think that would work as well.

A: Fixed it!
Instead of  @"ftp://xx.xx.xx.xx//'libary_name(myFile)'" where Library name: user_id.xyz.temp_lib and myFile: user_id.xyz.someFile, you have to use
@"ftp://xx.xx.xx.xx//'libary_name(someFile)'"  If you use the full MVS data set path on this command, you will get an error.

A: For the MVS ftp server, you don't use the MVS style dataset name.  Each node in the dataset name is treated as a directory.  For example, if you started at "/", you could:
chdir user_id
  chdir xyz
  chdir temp_lib
  ls
would get you a listing of all the members in the library user_id.xyz.temp_lib.
To upload, try @"ftp:/xx.xx.xx.xx/user_id/xyz/temp_lib/myFile".
To get the file in FB, you can use the DCbdsn command:
214-DCbdsn=data_set Specifies that FTP should allocate any new data sets
214-                with the same attributes as this data set. Data_set is
214-                either a fully qualified data set name in quotes
214-                or appended to the present directory name prefix.
214-                Blocksize, lrecl, recfm and retpd parameters will override
214-                the model data set characteristics if they are specified.
You can also use the Blocksize, lrecl or recfm options independantly.


text:
Q: Unknown CSS Appearing on Fieldset I am having the hardest time styling this fieldset. it seems to be picking up random styling that I didn't place on it. There is a random margin that is show in the inpsect and its pushing the label to a new line. Additionally its center aligned and I can't find any code that is tells it to do that.
https://sidecoinc.com/contact/
I've attached the code but this doesn't seem to be the problem.
I am trying to get it to just look normal. Check boxes with labels next to them and left aligned.
      <fieldset for="MSM_custom_Interests">
        <legend>What do you need help with?</legend>
        <input type="checkbox" class="custom_input" name="MSM_custom_JamesHardie" value="True">James Hardie

        <input type="checkbox" class="custom_input" name="MSM_custom_MarvinWindowsDoors" value="True">Marvin Windows & Doors

        <input type="checkbox" class="custom_input" name="MSM_custom_TimberTech" value="True">TimberTech

        <input type="checkbox" class="custom_input" name="MSM_custom_MoistureManagement" value="True">Moisture Management info

        <input type="checkbox" class="custom_input" name="MSM_custom_OutdoorLiving" value="True">Outdoor Living Options

        <input type="checkbox" class="custom_input" name="MSM_custom_Everything" value="True">Everything

        <input type="checkbox" class="custom_input" name="MSM_custom_Other" value="True">Other

     </fieldset>

#marketsharpmFieldSet input.custom_input {
  width: auto;
  height: auto;
}
#marketsharpmFormDiv input {
  border-spacing: 0px;
  margin: 0px;
  padding: 0px;
  space: 0px;
  display: block;
}
#marketsharpmFieldSet input {
  width: 100%;
  height: 32px;
}

A: The issue is the display block on the input - that is forcing the input to be the full width and so the label is pushed to the next line.
Change the display: block - to display: inline-block.... note that this will bring the checkboxes and labels to the same line - but you have styling somewhere that is centering the content so that will need to be resolved. I would also suggest adding a margin right to the checkbox (or margin-left to the label) to space them out a bit.
#marketsharpmFormDiv input {
  border-spacing: 0px;
  margin: 0px;
  padding: 0px;
  space: 0px;
  display: inline-block; // /changes this line
}

Effect of changing block to inline-block:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Local positioning system Let me start by stating that I am a student with very little experience so I am starting at square one, so please bear with me.
Requirements
I am looking to create a local positioning system between 1 transmitters and N receivers (3-6 most likely). This is in a outdoor space about 10m x 10m and I only care about 2D location. I would like accuracy to be within 0.2m or so. The area will be very flat and open and the only disturbance will be the sound of a small engine. The transmitter will be moving with the receivers remaining stationary (that's how I imagine it anyways). The inherent design of the systems requires the transmitter to be moving very slowly, roughly walking speed or slower.
Current Idea
Given my accuracy limitations GPS is out of the question, and given the idea of a moving transmitter I decided an IR sensor would not give me the multiple directions for multiple receivers I require. After all this I decided an ultrasonic sensor would most likely give me the result I require. As you can probably tell I'm still stuck in the design phase and want to solidify an idea that would give me closet to the desired results.
Question
Am I correct in thinking that I can use a combination of ultrasonic transmitters/receivers to triangulate the location of the moving transmitter? Is there possibly a better system for what I'm trying to do?
I wish I could bring more technical questions to the table, but the more technical information I look up the more I realize I need to understand the fundamentals of what I am trying to accomplish first.  I have very little practical information, so even links to readings or videos would be greatly appreciated.

A: Differential GPS may be able to get you good enough accuracy.

A: As a "Robotics" engineer myself, I can tell you right now that it is not a trivial problem. Your system of transmitters and receivers will work with at minimum 1 transmitter and 2 receivers, any more will just help with the redundancy and fusion of measurements to reduce error (get a more accurate position estimate and with lower uncertainty).
There are formula (essentially it is just trigonometry) but first you must get the time stamp (synchronized as close as possible, to get the best accuracy) from each of the receiver units, which gives you a "radius" for each receiver. These radii will overlap, and there will be a weird gap in between them all. This is basically where your transmitter is/was at the time of the signal.
The time taken for the ultrasonic ping to reach each receiver gives you the distance, because the time taken multiplied by the speed of sound in ambient air at whatever temperature you estimate, gives you an approximate distance traveled.
That works if you have synchronisation of clocks, without that you can do a difference between each receiver and their known locations to work out the same thing as before, using similar information.
You may be able to find examples/formula/concepts for this in robotics textbooks which cover topics on "Localisation". My professor (Prof. Peter Corke) has a nice textbook called Robotic Vision and Control which you may enjoy.

A: Personally I'd stick a high-def camera up a pole and use OpenCV, then just tell each subject where it is via a simple radio link.

A: Depending on your budget and how much time you can invest in this aspect of your project, the mentioned answers (computer vision, differential carrier-phase GPS, ultrasound) are all potentially viable.


text:
Q: Trying to send a registration request to to an API in xamarin Forms Am trying to connect to an API I built with the client version, running the client app with break points I can see that the data I pass in(signing up) gets passed down but when it get to the the PostAsync method that sends the data to the api the application breaks and I get 'system-net-webexception-failed-to-connect-to-localhost-127-0-0-1-44391' and an accompanying error that reads 'The selected debug engine does not support any code executing on the current thread (e.g. only native runtime code is executing)', there's no red highlight to indicate where the error is which makes this a real head scratcher for me.....
Some insight on the issue will be greatly appreciated.
Sub.Clicked += async (object sender, EventArgs e) =>
          {
              if (!Conection.IsConnected)
              {
                  await DisplayAlert("No Connection", "Please turn on or reset your data connection", "Cancle");

              }

              var entirs = new string[] { Email.Text, Password.Text, FN.Text, LN.Text, Phone.Text};

              var jcon = JsonConvert.SerializeObject(entirs);
              var contain = new StringContent(jcon, Encoding.UTF8, "aplication/json");
              message.Timeout = new TimeSpan(0, 0, 100);
              var outcome = await message.PostAsync("https://localhost:5001/api/v1/identity/Register", contain);

              if (outcome.StatusCode==HttpStatusCode.Created)
              {
                  await DisplayAlert("Success", "Entries have been loaded", "X");
                  Application.Current.MainPage = new NavigationPage(new Selection());
              }

              else
              {
                  await DisplayAlert("Failed", outcome.StatusCode.ToString(), "cancel");
              };
          };


text:
Q: Locale getDisplayLanguage broken in jlink Image Here an SSCCE:
public class Main {
    public static void main(String[] args) {
        Locale item = Locale.FRANCE;
        System.out.println("Locale: "+item+" displayed: "+item.getDisplayLanguage(Locale.GERMANY));
    }
}

When compiling and running it, it correctly displays
Locale: fr_FR displayed: Französisch

But if I now create a custom runtime image through jlink and run it with it, I get:
Locale: fr_FR displayed: French

No matter which Locale is used, it always falls back to the English one it seems. Perhaps I need an additional module for this? The runtime image is generated like follows:
jlink --module-path "..." --add-modules=java.desktop,java.logging,javafx.controls,javafx.graphics,javafx.fxml,javafx.base,javafx.media --output image

My JDK version:
$ java --version
java 11.0.2 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

A: As stated here, the java.base module only includes the English locale. To build a Jlink image which includes the other locales as well, one must add the jdk.localedata module.


text:
Q: google map cluster and richmarker The question is about google map's cluster and richmarker on ruby on rails
Recently I am developing a web application with Ruby on Rails,
I found a vital problem yesterday, here is my javascript:

//Build initialize Gmap and build markers on it
//initialize array
var map_infos = [];
//receive marker data from controller
map_infos = gon.map_infos;

function initialize() {
    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(25.026, 121.523)
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

//rmarker setting
    var rmarkers = [];
    for(var i = 0; i < map_infos.length; i++){
    var rmarker = new RichMarker({
        position: new google.maps.LatLng(
            map_infos[i]["marker_lat"],
            map_infos[i]["marker_lng"]
        ),
        content: '

',
        map: map
    }).setShadow('5px -3px 3px #555');
    rmarkers.push(rmarker);
    }
    var markerCluster = new MarkerClusterer(map, rmarkers);
}

google.maps.event.addDomListener(window, 'load', initialize);

But in the case above cluster function doesn't work!
It still show every single marker!
So I change richmarker to the google default marker like below:

var rmarker = new google.maps.Marker({
    for(var i = 0; i < map_infos.length; i++){
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(
        map_infos[i]["marker_lat"],
        map_infos[i]["marker_lng"]
    ),
    map: map
    });
    markers.push(marker);
    }
    var markerCluster = new MarkerClusterer(map, rmarkers);
});

Cluster works now!
So the question is:
How can I user richmarker and cluster in the meantime?

A: I was just trying to do the same thing and got it to work the first time through using the following code (in Angular but should be similar enough to you) maybe you need to pass more properties to the RichMarker?
$scope.dynMarkers.push(
          new RichMarker({
                        map: $scope.map,
                        position: position,
                        draggable: false,
                        flat: true,
                        anchor: RichMarkerPosition.MIDDLE,
                        content: '
some map marker
',
                    }));

then:
$scope.markerClusterer = new MarkerClusterer($scope.map, $scope.dynMarkers, {
            gridSize: 25
        });


text:
Q: open a .txt file in a .exe program I wrote a simple program with python. But in a line it's supposed to open a .txt file located in the same folder of exe program, unluckily it doesn't find it!
This is my code:
from tkinter import *

def evaluate(event):
  textfile = open('nomi.txt', 'r')
  nomi = textfile.read().split(' ')
  nome = str(entry.get())
  indice = [0, 1, 2, 3, 4, 5, 6]
  for x in indice:
     if nomi[x] == nome:
         if nomi[x]!=nomi[-1]:
             nome2 = nomi[x+1]
         else:
             nome2 = nomi[0]
  res.configure(text = "dovrai fare un regalo a " + nome2)

w = Tk()
Label(w, text="Il tuo nome:").pack()
entry = Entry(w)
entry.bind("<Return>", evaluate)
entry.pack()
res = Label(w)
res.pack()
w.mainloop()

I need to send this .exe to other people and I thought to put the .txt file in a .zip file with the .exe ...but I need it to read the .txt file!

A: open('nomi.txt', 'r') will try to open the file in your current working directory.
This means that your .txt file needs to be in the same folder you are working from. Note that may be different from where the actual script is, which is not relevant here.

A: I fix it by using askopenfilename to select manually the file I need!
So my code now looks like that, and it works:
from tkinter import *
from tkinter import filedialog

def evaluate(event):
    nome = str(entry.get())
    indice = [0, 1, 2, 3, 4, 5, 6]
    for x in indice:
        print(nomi[x])
        print(nome)
        if nomi[x] == nome:
            if nomi[x]!=nomi[-1]:
                nome2 = nomi[x+1]
            else:
                nome2 = nomi[0]
    res.configure(text = "dovrai fare un regalo a " + nome2)

root = Tk()
root.filename =  filedialog.askopenfilename(initialdir = "/",title = "Select
file",filetypes = (("txt","*.txt"),("all files","*.*")))
textfile = open(root.filename, 'r')
nomi = textfile.read().split(' ')

w = Tk()
Label(w, text="Il tuo nome:").pack()
entry = Entry(w)
entry.bind("<Return>", evaluate)
entry.pack()
res = Label(w)
res.pack()
w.mainloop()

A: You need to specify the folder the file is located in when you open it.  You haven't provided enough information for me to advise how to determine what the path to that folder is, if you can't just include it directly in the code.


text:
Q: Using Ruby and Twitter can I gather ALL of a user's timeline? I'm trying to retrieve a user's timeline. The api says you can get (at the most) 3,200 tweets. I only seem to know how to get 20 using this code:
def gather_tweets_from(user)
  tweets = []
  file = File.open("tweets_from.txt","w")
  client.user_timeline(user).each { |tweet|
    file.puts tweet.text
  }
end
gather_tweets_from(user)

Please help me out,
Thanks :)

A: The user_timeline function lets you specify certain options. What you're looking for is something like
client.user_timeline(user, :count => 200).each { |tweet|
  file.puts tweet.text

http://www.rubydoc.info/gems/twitter/Twitter/REST/Timelines:user_timeline

A: You can do it by setting max_id parameter http://www.rubydoc.info/gems/twitter/Twitter/REST/Timelines
#set max_id to max value
mnid = 999999999999999999
#set number of tweets you want to get
max_no_tweets = 3500
count = 0
while(count < max_no_tweets)
    #each loop gets 200 tweet
    client.user_timeline('elonmusk', :count => 200, :max_id => mnid).each do |tweet|
        puts(tweet.text) if tweet.is_a?(Twitter::Tweet)
        #to get the next 200 tweet
        mnid = [mnid,tweet.id].min
        count+=1
    end
end


text:
Q: Как правильно написать функцию клика разных элементов не дублируя его

$(".summary_1").click(function(){
 if ($("#hotel-facilities").is(":hidden")) {
   $("#hotel-facilities").slideDown("slow");
   $(".summary_1").addClass("open");
 } else {
  $("#hotel-facilities").hide("slow");
   $(".summary_1").removeClass("open");
 }
});
$(".summary_2").click(function(){
 if ($("#lodging_type").is(":hidden")) {
   $("#lodging_type").slideDown("slow");
   $(".summary_2").addClass("open");
 } else {
  $("#lodging_type").hide("slow");
   $(".summary_2").removeClass("open");
 }
});
.details {
 border-top: 1px solid #cdd0d2;
 border-bottom: 0;
 cursor: pointer;
}
.tab_content {
 display: none;
 position: relative;
 border-bottom: 1px solid #cdd0d2;
 width: 250px;
 user-select: none;
 outline: 0;
}
.is-hidden {
 display: none;
}
.summary_1, .summary_2 {
 font-size: 14px;
 padding: 14px 40px;
 position: relative;
 list-style-type: none;
 margin: 0;
 font-weight: 400;
}

.summary_1:before {
 /*-webkit-transform: translate(-50%,-50%) rotate(0);*/
 transform: translate(-50%,-50%) rotate(-90deg);
    will-change: translate,rotate;
}
.summary_2:before {
 /*-webkit-transform: translate(-50%,-50%) rotate(0);*/
 transform: translate(-50%,-50%) rotate(-90deg);
    will-change: translate,rotate;
}

.summary_1:after {
 transform: translate(-50%,-50%);
    will-change: translate,opacity;
}
.summary_2:after {
 transform: translate(-50%,-50%);
    will-change: translate,opacity;
}
.summary_1.open:before{ /* добавочный класс */
    transform:translate(-50%,-50%) rotate(-0deg);
    width:0;
}
.summary_2.open:before{ /* добавочный класс */
    transform:translate(-50%,-50%) rotate(-0deg);
    width:0;
}
.summary_1:after,
.summary_1:before {
 content: "";
 width: 14px;
 height: 2px;
 border-radius: 2px;
 background-color: #37454d;
 display: block;
 position: absolute;
 top: 50%;
 transition: all .2s ease-in-out;
 opacity: 1;
 left: 21px;
 contain: strict;
}
.summary_2:after,
.summary_2:before {
 content: "";
 width: 14px;
 height: 2px;
 border-radius: 2px;
 background-color: #37454d;
 display: block;
 position: absolute;
 top: 50%;
 transition: all .2s ease-in-out;
 opacity: 1;
 left: 21px;
 contain: strict;
}
.summary_1, .summary_2:hover {
 background: #ebeced;
    cursor: pointer;
}

Hotel facilities

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        24-hour reception (4923)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        24-hour room service (286)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Airport shuttle (602)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Beach umbrellas (2094)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Bungalows (152)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Business center (3052)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Casino (113)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Concierge (2187)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Conference rooms (2659)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Convenience store (1219)

Type of lodging

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Bed & Breakfast (427)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Camping Site (27)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Hostel (121)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Hotel (8967)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Motel (816)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Pension (243)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Serviced Apartment (493)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Vacation Home (3417)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Vacation Rental (11847)

Всем привет есть 2 блока  и при клике они открываются.Я для каждого блока написал свой класс и свой идендификатор.Мне нужно обьединить как то эти блоки.Чтобы не было дублированного кода.Почему?Потому что в сайте будет 9 таких блоков и для каждого написать summary_1, summary_2, summary_3, summary_4 ,summary_5 и т.д и дать свой стиль неправильно нужно чтобы был единый класс единый идентификатор если невозможно чтобы код так не дублировался . И все было написано изящно и правильно.

A: Если вы сами видите, что классы одинаковые, и логика работы одинаковая, то оставьте один класс и все.

$(".summary").click(function(){
    var acSel = '#' + $(this).attr('aria-controls');

    // можно так, если исходная анимация не нужна в точности
    // $(acSel).slideToggle('slow');
    // или как в вопросе
    if ($(acSel).is(":hidden")) {
        $(acSel).slideDown("slow");
    }
    else {
     $(acSel).hide("slow");
    }
    $(this).toggleClass("open");
});
.details {
 border-top: 1px solid #cdd0d2;
 border-bottom: 0;
 cursor: pointer;
}
.tab_content {
 display: none;
 position: relative;
 border-bottom: 1px solid #cdd0d2;
 width: 250px;
 user-select: none;
 outline: 0;
}
.is-hidden {
 display: none;
}
.summary {
 font-size: 14px;
 padding: 14px 40px;
 position: relative;
 list-style-type: none;
 margin: 0;
 font-weight: 400;
}

.summary:before {
 /*-webkit-transform: translate(-50%,-50%) rotate(0);*/
 transform: translate(-50%,-50%) rotate(-90deg);
    will-change: translate,rotate;
}
.summary:after {
 transform: translate(-50%,-50%);
    will-change: translate,opacity;
}

.summary.open:before{ /* добавочный класс */
    transform:translate(-50%,-50%) rotate(-0deg);
    width:0;
}

.summary:after,
.summary:before {
 content: "";
 width: 14px;
 height: 2px;
 border-radius: 2px;
 background-color: #37454d;
 display: block;
 position: absolute;
 top: 50%;
 transition: all .2s ease-in-out;
 opacity: 1;
 left: 21px;
 contain: strict;
}

.summary:hover {
 background: #ebeced;
    cursor: pointer;
}

Hotel facilities

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        24-hour reception (4923)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        24-hour room service (286)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Airport shuttle (602)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Beach umbrellas (2094)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Bungalows (152)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Business center (3052)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Casino (113)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Concierge (2187)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Conference rooms (2659)

        <input type="checkbox" id="hotel-facilities-200" name="hotel-facilities-200" class="checkbox">
        Convenience store (1219)

Type of lodging

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Bed & Breakfast (427)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Camping Site (27)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Hostel (121)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Hotel (8967)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Motel (816)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Pension (243)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Serviced Apartment (493)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Vacation Home (3417)

        <input type="checkbox" id="lodging_type-200" name="lodging_type-200" class="checkbox">
        Vacation Rental (11847)


text:
Q: What's the difference of source complile or use apt? For example, I want to install glog, I could use
sudo apt-get install libgoogle-glog-dev
or
git clone https://github.com/google/glog

./autogen.sh && ./configure && make && make install

What's the difference?
I'll appreciate it if you help me.

A: In
sudo apt-get install libgoogle-glog-dev,
It installs and maintains programs and other collections of files (data, documentation, etc.) in the form of packages.
while in second one you first download the source from Github repository and then run various shell files which get it installed on your system.
I hope it helps you.


text:
Q: Why inside ref's change behaves inconsistantly from inside to outside? def foo(l):
   r.append(l)
   l[0], l[1] = l[1], l[0]
   r.append(l)

r = []
l = [0, 1]
print(l);
foo(l)
print(l);
print(r);

print out:
[0, 1]
[1, 0]
[[1, 0], [1, 0]]

As I know python passes arguments by assignments, as a new ref to the outer [0, 1], the inner l with swap like this does not create a new object but change the object the inner refers to, so as the outer print of l acts similarly the behaviour was assumpted.
But the pair of r.append(l) seems add the object with the same content each time. Is is beacase of features like lazy loading or some?
Of course, this may be solved by using methods like r.append(x for x in l), which in my opinion, add a new list object to r. But still, I want to figure out what is the behvaiour defined in python that we add an item (same ref to an object) to a list, and what happened when we ask for the list content.

A: This is a good question. Let's break down what is happening.
One of the tools you have when you get questions like this is the id built-in function. id is a way of checking whether the object is the same as a previous one or not.
Let's use id in your code.
def foo(l):
   print("The ID of r in the function foo is {}".format(id(r)))
   print("The ID of l in the function foo is {}".format(id(l)))

   r.append(l)
   print("The ID of r in the function foo after the append is {}".format(id(r)))
   print("The ID of the the items in r: {}, after first append".format(id(r[0])))
   l[0], l[1] = l[1], l[0]
   print("The ID of l in the function foo after the swap is {}".format(id(l)))

   r.append(l)
   print("The ID of r in the function foo after second append is {}".format(id(r)))
   print("The ID of the the items in r: {}, {} after second append".format(id(r[0]), id(r[1])))

r = []
print("The ID of r in the beginning is {}".format(id(r)))
l = [0, 1]
print("The ID of l in the beginning is {}".format(id(l)))
print(l)
foo(l)
print(l)
print("The ID of l after the foo call is {}".format(id(l)))

print(r)
print("The ID of r after the foo call is {}".format(id(r)))
print("The ID of the the items in r: {}, {}".format(id(r[0]), id(r[1])))

My output (yours will vary) is:
The ID of r in the beginning is 4374077736
The ID of l in the beginning is 4374122152
[0, 1]
The ID of r in the function foo is 4374077736
The ID of l in the function foo is 4374122152
The ID of r in the function foo after the append is 4374077736
The ID of the the items in r: 4374122152, after first append
The ID of l in the function foo after the swap is 4374122152
The ID of r in the function foo after second append is 4374077736
The ID of the the items in r: 4374122152, 4374122152 after second append
[1, 0]
The ID of l after the foo call is 4374122152
[[1, 0], [1, 0]]
The ID of r after the foo call is 4374077736
The ID of the the items in r: 4374122152, 4374122152

What this tells us is that there is always only 2 variables here.
Even within r. You are appending the same object twice. And this object can be changed externally as well.
So whenever it changes, it changes within your containing list as well.
Each item in r is pointing to the same l.

A: For those who are not familiar with Python, I tried to write a self-explainatory C++ code:
#include <iostream>
#include <vector>

using namespace std;

class A {
public:
    void setValue(int value) {
        this->value = value;
    }

    int getValue() {
        return this->value;
    }
private:
    int value;
};

int main() {
    vector<A*> list;
    A* obj = new A();

    obj->setValue(1);
    list.push_back(obj);
    obj->setValue(2);
    list.push_back(obj);
    obj->setValue(3);
    list.push_back(obj);

    for (auto item : list) {
        cout << item->getValue() << endl;
    }
}

prints out:
3
3
3

It's almost the same thing that was done with Python in question.


text:
Q: What does "the author's title" mean here? The sentences below are from In France, They Call It 'Happiness Therapy'

In an online poll the Web site Newsring recently asked its readers if
  they were pro or con film title translation; 78 percent responded
  against.
In 2003, Mr. Ernst was in charge is distributing Stephen Frears's
  "Dirty Pretty Things." "It was a difficult decision," he said. "It was
  the author's title, and a beautiful one, so we didn't want to change
  it. It was also quite easy to understand."
In the end, they went with the same title, but with "Loin de chez eux" (Far From Home) as a subtitle.
And sometimes, keeping the English titles, as complicated as it may
  be, works out fine. The perfect example: "Eternal Sunshine of a
  Spotless Mind," which kept its mysterious title and did very well at
  the French box office.

I know "Dirty Pretty Things" is a English movie's title and  Mr. Ernst was unwilling to translate it to French.But what does" the author's title" mean here ? Does it mean" the original title" or "a famous title" or something else?

A: The original title is the first title given to a work.  It's possible, though not common, for someone besides the author to give a work its first title.
The author's title is the title the author came up with.  It may or may not be the original title, but most of the time it is.

A: It means the title given from Stephen Frears, the director of the movie. You can also say the original title, since they are talking about translating the title.


text:
Q: Is a facet_grid/wrap required to group boxplots by a variable other than used for fill/colour? I've run two experiments, some replicating the conditions of a previous set. I have a column for the unique lot ID as well as another column containing the ID from experiment 1 which the lots from experiment 2 replicates. Here's some example data stored like this:
test <- data.frame(var1=c(rep("A",4), rep("B",4), rep("C",4), rep("D",4)),
                   var2=rep(c(rep("A",4), rep("B",4)),2),
                   value=runif(16,1,5))

Here's my ggplot code:
ggplot(test, aes(x=var1, y=value, fill=var2)) + geom_boxplot()

This gives me the lot IDs arranged according to var1's factor order.

I'd like the A's from var2 side by side and the B's from var2 side by side. Is the only way to do this by using facet_grid or facet_wrap?
 ggplot(test, aes(x=var1, y=value, fill=var2)) + geom_boxplot() +
        facet_grid(. ~ var2, scales="free_x")

I tried adding group=var2 but that gives me overlapping and very wide boxplots, which I also don't understand:
ggplot(test, aes(x=var1, y=value, group=var2, fill=var2)) + geom_boxplot()
Warning message:
position_dodge requires non-overlapping x intervals

I can use facetting; I'm mostly asking the question as I was surprised when I couldn't group  how I expected. I also looked in the examples for geom_bar() for more grouping approaches but it seems most people aren't grouping things this way.
Feel free to provide other input on how one might approach this. I'm simply looking to compare pairs of test results to make it easy to see whether the replicate matches the original trial.

A: A cheats method using interaction and adjusting the scale_x_discrete labels
 ggplot(test, aes(x=interaction(var1,var2), y=value, fill=var2)) +
  geom_boxplot() +
  scale_x_discrete(name = 'var1',breaks = c('A.A','C.A','B.B','D.B'),
                   labels = c('A','C','B','D'))

EDIT Thanks to @Andrie's comments
Or you can create an appropriately ordered factor, or (unordered) factor with levels specified in the correct order.

*

*ggplot2 respects the order of the factor levels (whether in an ordered factor or not).

*R will order the levels a factor lexicographically by default, so for any other order, you will need to specify it.

.
library(plyr) # for arrange
var1_order <- unique(as.character(arrange(test,var2)[['var1']]))

test$var1_order <- ordered(test$var1, levels = var1_order)
## or
test$var1_order_2 <- factor(test$var1, levels = var1_order)
## so that
ggplot(test, aes(x=var1_order_2, y=value, fill=var2)) +
 geom_boxplot() +
 xlab('var1')
## or
ggplot(test, aes(x=var1_order, y=value, fill=var2)) +
 geom_boxplot() +
 xlab('var1')

Will both give the same result
EDIT -- Another approach
You could have your x axis as var2 and fill by var1, which will order by var2 then dodge and fill by var1
  ggplot(test, aes(x=var2,y=value)) +
   geom_boxplot(aes(fill = var1))


text:
Q: How to check at least one radio button is selected in a td tag in javascript

RNO.1
    <input type="radio" id="att1" name="att1" value="P"/>Present
    <input type="radio" id="att1" name="att1" value="A" />Absent
    <input type="radio" id="att1" name="att1" value="L" />Leave

RNo.2
    <input type="radio" id="att2" name="att2" value="P"/>Present
    <input type="radio" id="att2" name="att2" value="A" />Absent
    <input type="radio" id="att2" name="att2" value="L" />Leave

RNo.3
    <input type="radio" id="att3" name="att3" value="P"/>Present
    <input type="radio" id="att3" name="att3" value="A" />Absent
    <input type="radio" id="att3" name="att3" value="L" />Leave

I want to check at least one radio button is selected in each td using javascript also RNo's will increase i just put few. Please help me.


text:
Q: jquery is not working in wordpress template this is my test form,in this form i want to apply change function and keyup functions,but it doesnt work

<form>

        Choose group
        <select name="group " id="sktest">
            <option value="group1">Group 1</option>
            <option value="group2">Group 2</option>
            <option value="group3">Group 3</option>
        </select>

        G1 option <input id="sk" type="text" name="opt1">

        G1/G2 option<input id="sk" type="text" name="opt2">

        G2/G3 option<input id="sk" type="text" name="opt3">

        G3 option<input id="sk"type="text" name="opt4">

</form>

<?php get_footer(); ?>

i am trying to alert messages but it doesent work .please help me/...

A: First of all Id should be unique. So in case you needed to bind same function with multiple elements, use class then.
Second, put your js function inside $(document).ready
I checked when putting your function in $(document).ready() plus if you have mutliple ids it will fire only for the first element.
It has nothing to do with wordpress
$(document).ready(function(e)
{
alert('jQuery loaded');
$("#sktest").change(function(){
    alert('ok');
});
$("#sk").keyup(function(){
    alert('ok');
});
})

A: Hi @Pankaj Waghmare user JQuery instead of $.
Example : JQuery(document).ready();.
Hope this helps u.


text:
Q: Is an alternative version of each page in a site a valid approach to WCAG 2.0? We are working on a new project that requires a complex design, however the client also wants it to be WCAG 2.0 compliant level AA. So we came up with the idea of adding a toolbar at the top of the each page with a button saying something along the lines "view this page enhanced for accessibility" and then store the preference as a cookie.
The question is if this is considered discrimination or a technique that would be easily missed and defeat the goal? We have ways of making this switch button very obvious, but we haven't seen any site doing something like this, nor have found any documentation in favor or against it.

A: Technically, yes - it's a valid approach to WCAG 2.0 - but you won't find many accessibility specialists recommending this.
The WCAG 2.0 supporting documents provide a lot of context for this, in Understanding Conforming Alternate Versions.  However it clearly advises against this approach, at the end of the section called "Why permit alternate versions?":

Note that providing an alternate version is a fallback option for conformance to WCAG and the preferred method of conformance is to make all content directly accessible.

Compare the reasons given there to the situation with your own website, and only go down this route if you're certain you can't achieve conformance in the main version.  If you can make the majority of your pages accessible in the main version, it's OK to have alternative versions for a few pages.
Part of your question concerns discrimination:

The question is if this is considered discrimination or a technique that would be easily missed and defeat the goal?

WCAG 2.0 doesn't really address discrimination per se, but local statutes likely do.  This isn't the place for legal advice.
My own view is that going to lots of effort to provide (and maintain) alternative versions doesn't really amount to discrimination, but it doesn't aspire to inclusion either.  Imagine a public library: an old building, with steps leading up to a grand front entrance.  Pedestrians can stroll inside, enjoy the beautiful atrium, see posters about current events, talk to a librarian, or just go straight to the books.  A wheelchair user has to go to the rear entrance, then ring a bell for a librarian to come and let them in.  No fancy atrium to enjoy.  The librarian has to let them out again, too.  While the library is accessible for wheelchair users, the experience is a bit second-class; it's accessible by "alternative accommodations". Ideally the grand front entrance would be accessible to wheelchair users, but the architecture has a protected status.  Websites are easier to improve than buildings, so it's better to avoid alternative versions.
Your mention of a "toolbar" to provide "enhanced accessibility" is worth exploring a bit further.  Are your alternative versions really fully-fledged pages, or merely the same page with some tweaks applied? Providing customization options for the user is also a valid approach - see the Fluid Infusion Preferences Framework project for an example of this.  The relevant WCAG techniques are:

*

*C29: Using a style switcher to provide a conforming alternate version

*SCR38: Creating a conforming alternate version for a web page designed with progressive enhancement

*SVR4: Allowing users to provide preferences for the display of conforming alternate versions.

A: Two pages is acceptable but a bad idea, maintainability, SEO etc. are all factors as have been mentioned.
But what hasn't been mentioned is simply having different style sheets for accessibility.
Provided your html mark-up is valid and logically structured then to make the page accessible is a 'simple' case of adding aria attributes - that covers users with screen readers.
You said this was a complex page so the 'constraints' of designing for disabled users may make you simplify and improve components along the way and so benefit the client anyway. Changing your HTML to be accessible not only benefits your disabled users but you will find it makes the site easier to user for able bodied users, so that's a plus.
Once your HTML is valid and adjusted for accessibility to screen readers the other parts of accessibility (for partially sighted, colour blind etc.) are easily achieved with a different style sheet (or several for different scenarios.)
Disabled users need many different things but the key focus should be that the site is usable at 400% zoom on a 1920 * 1080 screen, colours can be changed, fonts can be changed and animations can be disabled for users with cognitive impairements.
This can all be handled with CSS.
What I did on my own site was to have a standard style sheet without animations, standard colours etc. Then a seperate style sheet for:

*

*animations (included by default)

*colours (over-riding standard colours without the use of !important)

*No JavaScript - as this can be a real issue for certain things and screen readers (i hide certain elements that would cause confusion without javascript enabled)

This is augmented by a seperate settings page where users can select font size, colours, font family, animations or not, images or not etc. stored in localstorage and then processed into some simple classes on the body on each page load that can be used for fine-grained control over items.

A: This is covered by the following WCAG technique : G136: Providing a link at the beginning of a nonconforming Web page that points to a conforming alternate version
This could be very cool, but it's not realistic.
20% of the population have direct benefit for accessibility:

*

*using zoom,

*getting correct contrast (color blindness, ...),

*having readable fonts (dyslexia),

*using simple language (foreigners, cognitive disabilities, deaf born people),

*using keyboard accessible controls (motor impairment due to age or accident).

Definitely, if you manage to provide an accessible version for 20% of the population, why would you want to hide it ?
Is because I may be dyslexic that I would want to have an ugly black and white page?
If you want to provide a toolbar, then you should give different options : enhance the page for color blind people, enhance for blind people, enhance for low vision, enhance for screen magnifiers, enhance for dyslexic, enhance for motor impairments, ...

A: It's generally a bad idea to double every page of your website. You'd better make the primary site accessible.
Don't forget that it will double your maintenance work.
It will also eventually happen, perhaps tomorrow or perhaps in 3 years, and this despite all the care you can have, that an accessible page will be out of date compared to the normal version, because someone just forgot to do something somewhere at some moment in the organization managing the site.
An oversight can have incidious consequences and you will probably take a long time to notice it, and if ever you become aware of it.
Note that if you can update an accessible page automatically when a normal one is modified, you can very probably make the normal site accessible at the first place.
Several studies and sureveys (example: webaim) show that, if a text only or more accessible version of a page is available, most of the users for which it could be useful don't open it at all.
Beside the possible difficulty to find the link or button, the main reason for this is because they basicly know that such pages are likely to be forgotten, out of date, buggy, or not that carefully maintained as the normal ones.


text:
Q: Nautilus right click script for base64 i would like to add nautilus script for right click,like convert selected file with base64 but no luck.Regular command in terminal is like:
base64 input.jpg output.txt

This is my closest script to do it;
#!/bin/sh
echo "$NAUTILUS_SCRIPT_SELECTED_FILE_Path" | base64 > Base64

But it gives the path of file as base64.
Can anybody help me about this?

A: Your original script has a couple issues:

*

*"$NAUTILUS_SCRIPT_SELECTED_FILE_Path" should be all capitalized and spelled differently, as in "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS".

*echo "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | base64 will only encode the string "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" and that's it. If you want to encode a file, you need to pass that variable on via xargs or better yet - pass it directly. base64 can take files as  arguments , thus base64 "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" is what you really want to do. No pipes here, no echo.

Below I provide alternative and fairly simplistic approach
Script
#!/bin/bash
for item in "$@"
do
   file=$(basename "$item" )
   base64 "$item" > "$HOME/$file.base64"
done

Instructions

*

*Place this file into ~/.local/share/nautilus/scripts/ directory

*ensure it is executable with chmod +x  <path to script here> command.

*Select the files that you want, right click , and go to scripts submenu. Select your script.

*Once the the script is done, each base64 encoded file will be placed into your home folder, with original filename and .base64 extension. You may wish to alter the script to create .base64 files in the same directory, which is totally fine, but it might be a problem if you do not have permission to create files in that directory.
Of course this script is slightly simplistic. I've created a bit more involved script in Python3 , which you can find on my GitHub repository for nautilus scripts. It does a bit more than the other scripts -  checks for file type, show info and error popups,etc.

A: I am assuming you can already add custom script to nautilus and only need the right script to do the actual work, if that be the case then try this script:

#!/bin/bash
# Generating base64 files from nautilus
m=0 # counter
while [ -n "$1" ] && [ -f "$1" ]
do
   echo " " >> output.txt
   echo "$1" >> output.txt
   base64 "$1" >> output.txt
   echo " " >> output.txt
   m=$(($M + 1))
   shift
   echo " " >> output.txt
done
zenity --info --text="Operations finished and "$m" file(s) encoded"
exit 0

Please make file executable with:
chmod +x /path/to/script

Explained:

*

*-n "$1" checks if the values are greater than 0, ie not 0

*-f "$1" checks if file exists and is regular file.

*shift moves through the given arguments

*m=$(($m + 1)) adds 1 to 0 initial count value to keep track of number of files being converted

*zenity displays a dialogue box to indicated end of operations.

A: Thank you for all guys,i did two scripts with your help and suggestions for encode and decode.
Encode:
#!/bin/bash
for item in "$@"
do
   mkdir /yourpath/encode
   file=$(basename "$item" )
   base64 "$item" > "/yourpath/encode/$file-base64"
done

Decode:
for item in "$@"
do
   mkdir /yourpath/decode
   file=$(basename "$item" )
   name=`echo $file | cut -f1 -d'-'`
   base64 -d "$item" > "/yourpath/decode/$name"

done


text:
Q: draw gradient color for form border i want to ask how do i add another color to the gradient color. iam currently using this code
  private void add3_Paint(object sender, PaintEventArgs e)
    {
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(this.ClientRectangle, Color.LightPink, Color.Gold, System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal);
        e.Graphics.DrawRectangle(new System.Drawing.Pen(brush,10), this.ClientRectangle);
        brush.Dispose();
    }

the result was like this

for the purple was panel control using dock bottom, please ignore it !.
what iam asking is as you can see iam using gradient color light pink and gold. but i want to add another color, e.g add another color green and add another color red (any slot for color) but the code i use only accessible for two color


text:
Q: pg_dump password in python I have a ubuntu remote server say 172.123.342.12. I want to take backup of a postgresql database on my local machine via a python script.
My Script is:
def backUp(self):
        Pass = 'fb2024d4'
        os.putenv("PGPASSWORD",Pass)
        dt = datetime.now()
        format = "%Y_%b_%d"
        cur_time = dt.now()
        form_time = cur_time.strftime(format)
        backup_str = "C:\\Bitnami\\odoo-8.0-7\\postgresql\\bin\\pg_dump.exe --format=c -h 172.123.342.12 -p 5432 -d new_db -U bn_openerp > C:\\Users\\n\\Desktop\\Odoo_Backups\\%s.dump" %form_time
        os.system(backup_str)
        print ("Backup Created in Desktop")
        box.showinfo("Information", "Backup Created")

backup()

It does nothing. Some help will be appreciated.
EDIT: The Script works on a database on windows as i am using admin account. So it does not asks for password. But When i try to backup a database from remote ubuntu server. It asks for password.
I have tried following solutions:
1.) SET PGPASSPASSWORD = C:\foo\bar..\pgpass.conf.
2.) os.putenv("PGPASSWORD","password")
3.) PGPASSWORD='password' pg_dump.exe -h localhost.....

No one worked for me.

A: I was able to use a python script to create a dump file using pg_dump.exe:
filename = 'C:/Path/To/File/mydb_dump.sql'
pgDump = 'C:/Program Files/PostgeSQL/9.5/bin/pg_dump'

subprocess.Popen('"{}" -h 127.0.0.1 dbname > "{}"'.format(pgDump, filename), shell=True)

A few things to note:
I STRONGLY CAUTION AGAINST USING shell=True !!!
There is a huge security hazard with possible shell injections as per the documentation.
I'm not sure if will work with a remote Ubuntu server, but I couldn't see why not if all permissions and sharing is setup properly.

I know this is pretty old, but I hope it helps.


text:
Q: Загрузка файлов на сервер Нужно загрузить файл на сервер(картинку).
Имею кучу полей для заполнения, заполнили и жмём button, он через onclick шлёт синхронный запрос на сервер и получает ответ, в итоге товар добавлен и отображен.
Вопрос в том, как прикреплять к товару, картинку. Если через  то нужна Форма, а мне она не нужна, у меня всё отправляет обычный button через javacript(ajax).
На сервере папка Images, хотелось бы как-то туда загружать изображение.
Вот пример как я добавляю без картинки( а надо с картинкой)
$.ajax({
        url: EXECUTOR,
        data: "title=reizen&size=19&width=20&age=12",
        type: "POST",
        dataType: "JSON",
        async: false,
        success: function (data) {

как здесь можно указать картинку, что бы в php-файле её отловить к примеру is__uploaded__file

A: плагин https://github.com/blueimp/jQuery-File-Upload
A: Отличнейшая статья об использовании FileReader: https://developer.mozilla.org/ru/docs/Using_files_from_web_applications#Example.3A_Uploading_a_user-selected_file


text:
Q: Parameter 'login_failure_type ' not returned for Login event in Reports API I am trying to find the login_failure_type for a login_failure event using the G Suite Admin SDK Reports API (reference: https://developers.google.com/admin-sdk/reports/v1/appendix/activity/login?#login_failure). For all events I pull through this request, the login_type and login_challenge_method paremeters are included, but the login_failure_type parameter is omitted.
Does the login_failure_type parameter require an extra request parameter to get back or is this parameter no longer available?


text:
Q: Is it possible to convert 'dynamic' excel formulas to python code? Is it possible to convert excel formulas to python code? For example:
     "=TEXT(SORT(PROPER(UNIQUE(FILTER("
            "ws_1!A:A,ws_2!B:B=ws_3!C3"
            ')))), "")'

Or it is not possible. I was looking into Pycel, xlcalculator, formulas module. But unfortunately i cannot find more complicated example than sum(A,B).
Probably i could do it with pandas, but it won't work constantly in spreadsheet. Or can i save some python script instead formula to cell?
if you have any idea how to translate easier formulas eg. or any library that can do it, I would be grateful for the tips :
'=IFERROR(VLOOKUP(C2,ws!A2:B3,2,0), "Invalid")'

My motivation is to avoid a long excel formula in python code. And make it testable


text:
Q: Yii2 - Ignore validation if In my Yii2 project, I have related models. Example: A model Customer would have an attribute address_id that relates to another model Address. In the Customer model have the exist validator that checks that the row exists in the address table.
Typically, on create or update, this validation is ignored if address = null. My problem is that sometimes FE would send the address = 0 indicating the absence of an address.
In this case, I need to not only ignore validation, but to set address = null. This can be done beforeSave of course, but I'm trying to check if there's some built-in way through which I can do this

A: You can use the filter validator for normalization of an input data. For example:
class Customer extends ActiveRecord
{
    public function rules()
    {
      return [
          ['address_id', 'filter', 'filter' => function ($value) {
              return $value == 0 ? null : $value;
          }],
          // other validators
      ];
    }
}


text:
Q: python 2.7 to python 3.2 string formatting error I have this piece of python code:
args   =(12, 45, 7854)
2 result = 123
3 answer = 456
4 print 'Test with data: ', args, ' result: ', result, ' answer: ', answer

Now when I run this with python2.7.3 I get this:
Test with data:  (12, 45, 7854)  result:  123  answer:  456

But when i use python3.2.3 I get this error:
print 'Test with data: ', args, ' failed result: ', result, ' answer: ', answer
                       ^
SyntaxError: invalid syntax

I looked for different ways of concatenating or formatting that string but using + or the %s  gives the same error.
Any help, thanks in advance.

A: print is a function in py3x:
print ('Test with data: ', args, ' failed result: ', result, ' answer: ', answer)

A: In python 3+ you need to put print( ) because the print keyword in 2+ is now a function in 3+.
Here are the Python Docs Regarding this.


text:
Q: XML Log file regex A legacy system I cannot change is pumping out 5 Gig of mostly awful XML logs per day and blowing my ingestion licence.
There are 2 classes of verbose errors occurring 1000+ times a minute, but every few minutes one genuinely interesting entry.
I'd like to drastically shorten the repeating entries in sed, and retain the interesting ones untouched
So what I need
1. Regexes to match each of the 2 classes of annoying log entry  (e.g. ...'decimal'... and ...'DBNull'... but not the occasional interesting ones).

   One regex to match each annoying error class is fine, I can do 2 sed passes

2. I need a capture group with the timestamp so I can replace the long XML lines with a succinct version - but with the correct timestamp so as not to lose fidelity.
I've gotten as far as this to match the  and the capture created date:
(?:<Log).*?(createdDate="\d{2}\/\d{2}\/\d{4}.\d{2}:\d{2}:\d{2}").*?(?:decimal).*?(<\/Log>)

which is close, but suffers from a kind of reverse greediness where I match the from 'decimal' to a an opening Log statement several entries earlier
Have played around negative look-behind but just given myself a severe headache
Sample Data
<Log type="ERROR" createdDate="11/09/2015 08:13:14" >
 <![CDATA[ [108] -- much cruft removed-- SerializationException: There was an error deserializing the object of type Common.DataCtract.QResult. The value '' cannot be parsed as the type 'decimal'. ---> System.Xml.XmlException: The value '' cannot be parsed as the type 'decimal'. ---> System.FormatException: Input string was not in a correct format.
  ]]></Log>

<Log type="ERROR" createdDate="11/09/2015 08:13:13" >
 <![CDATA[ [108] -- much cruft removed-- SerializationException: There was an error deserializing the object of type Common.DataCtract.QResult. The value '' cannot be parsed as the type 'decimal'. ---> System.Xml.XmlException: The value '' cannot be parsed as the type 'decimal'. ---> System.FormatException: Input string was not in a correct format.
  ]]></Log>

<Log type="ERROR" createdDate="11/09/2015 08:13:12" >
 <![CDATA[ [129] Services.DService.D.FailedToAddRQ(Exceptionex, RQEntityrQ, RHeaderEntityrHeader, StringPRef, ): FailedToAddRQ()...with parameters [pRef:=123,0,1], [rQ.AffinityCode:=],[Q.thing=thing][rQ.AffinityRQDT:=123],[rHeader.RHeaderIDPK:=123],[rQ.UWriteIDFK:=]
  Data.DataAccessLayerException: Conversion from type 'DBNull' to type 'Long' is not valid.
Parameters:
 [RETURN_VALUE][ReturnValue] Value: [0]
 ---> System.InvalidCastException: Conversion from type 'DBNull' to type 'Long' is not valid.
 ]]></Log>

 <Log type="ERROR" createdDate="11/09/2015 08:13:11" >
 <![CDATA[ [129] Services.DService.D.FailedToAddRQ(Exceptionex, RQEntityrQ, RHeaderEntityrHeader, StringPRef, ): FailedToAddRQ()...with parameters [pRef:=123,0,1], [rQ.AffinityCode:=],[Q.thing=thing][rQ.AffinityRQDT:=123],[rHeader.RHeaderIDPK:=123],[rQ.UWriteIDFK:=]
  Data.DataAccessLayerException: Conversion from type 'DBNull' to type 'Long' is not valid.
  ]]></Log>

 <Log type="ERROR" createdDate="11/09/2015 08:13:10" >
 <![CDATA[ [231] An actual interesting log entry with a real error message ]]></Log>

<Log type="ERROR" createdDate="11/09/2015 08:13:09" >
 <![CDATA[ [108] -- much cruft removed-- SerializationException: There was an error deserializing the object of type Common.DataCtract.QResult. The value '' cannot be parsed as the type 'decimal'. ---> System.Xml.XmlException: The value '' cannot be parsed as the type 'decimal'. ---> System.FormatException: Input string was not in a correct format.
  ]]></Log>

A: Not sure what you are exaclty looking for, but this is an example of how you can isolate <Log...</Log> blocks and proceed to a replacement:
sed '/^<Log /{:a;/<\/Log>/!{N;ba;};s/>.*\(decimal\|DBNull\).*</>\1</}' file.log

details:
/^<Log / { # condition: a line that starts with "<Log "
    :a;    # define the label "a"
    /<\/Log>/! { # condition: if the line doesn't contain "</Log>"
        N;       # append the next line to the pattern space
        ba;      # go to the label "a"
    };
    s/>.*\(decimal\|DBNull\).*</>\1</ # replace the block
}

(I assumed <Log are always at the start of the line unlike records at sec 10 and 11, that are probably typos.)


text:
Q: Use Quarter in GROUP BY in SQL Server I am trying to use Quarter inside date part in my query with Group By but it isn't working for me.
This is my query:
SELECT
    Id, Name,
    Quarter1 = (SELECT COUNT(TS.Id) FROM TS WHERE TS.Status = STATUS.StatusId GROUP BY DATEPART(QUARTER,TS.EndDate)),
    Quarter2 = (SELECT COUNT(TS.Id) FROM TS WHERE TS.Status = STATUS.StatusId  GROUP BY DATEPART(QUARTER,TS.EndDate)),
    Quarter3 = (SELECT COUNT(TS.Id) FROM TS WHERE TS.Status = STATUS.StatusId GROUP BY DATEPART(QUARTER,TS.EndDate)),
    Quarter4 = (SELECT COUNT(TS.Id) FROM TS WHERE TS.Status = STATUS.StatusId GROUP BY DATEPART(QUARTER,TS.EndDate))
FROM
    TS
INNER JOIN
    STATUS ON TS.Status = STATUS.StatusId
GROUP BY
    Id, Name

I need to by my data result like in example
Id   Name    Quarter1 Quarter2 Quarter3 Quarter4
---- ----    -------- -------- -------- --------
1    STATUS1    1       2           3       4
2    STATUS2    4       12          66      80
3    STATUS3    5       10          23      9
4    STATUS4    9       7           90      99
5    STATUS5    20      5           88      22

A: You don't need inner queries - just count a conditional expression:
SELECT     Id,
           Name,
           Quarter1 = COUNT(CASE DATEPART(QUARTER, TS.EndDate) WHEN 1 THEN 1 END),
           Quarter2 = COUNT(CASE DATEPART(QUARTER, TS.EndDate) WHEN 2 THEN 1 END),
           Quarter3 = COUNT(CASE DATEPART(QUARTER, TS.EndDate) WHEN 3 THEN 1 END),
           Quarter4 = COUNT(CASE DATEPART(QUARTER, TS.EndDate) WHEN 4 THEN 1 END)
FROM       TS
INNER JOIN STATUS ON TS.Status = STATUS.StatusId
GROUP BY   Id, Name


text:
Q: Clearance and creepage requirements in EU I'm looking for the clearance and creepage requirements between live voltage (230V) and SELV (Safety Extra Low Voltage) in the EU.
I had a look at this and other questions, but I rarely see numbers mentioned, and when I do see them, they often contradict each other. So far I've seen clearance distances of 3mm, 5.5mm and 6mm. For creepage I haven't any numbers at all.
So, what is required?
(PS: can somebody add the selv tag? Thanks)

A: Here is a diagram that should help: -

Picture taken from this document.
Please also note that creepage distances might have to be bigger dependent on your pollution category and your material group. See this document for further info.
There is also this calculator - I have tried it and for 250V AC, the protection distances seem to be right i.e. basic creepage is 2.5mm with 2.5mm for supplementary making a 5mm total for reinforced. Ditto the clearance figures - they add up to 4.0mm for reinforced: -


text:
Q: Каким образом вывести строку из prompt? Пожалуйста, подскажите, каким образом добавить строку в документ из prompt?

A: var string = prompt('String value');
document.write(string);

переменная string будет содержать значения из prompt,а дальше выводите куда вам нужно

A: Обратите внимание на тип возвращаемого значения (Return Value): String
А также тут


text:
Q: Prove that if $~x,~y \in \mathbb R~$, $~f(x)=f(y)~$ and $~x=y~$. $~f:\mathbb R\to \mathbb R~$ is a function on $~\mathbb R~$, and $~\{f_z\}~$ is a sequence of real valued functions on $~\mathbb R~$ defined by $~f_1(x)=f(x), ~x  \in \mathbb R ~$ and $~f_{z+1}=f[f_z(x)] ,~x ~\in \mathbb R ,~~~ z=1,2,3,4,\cdots~$
Assume there exists a positive integer $~z_0~$ such that $~f_{z_0}(x)=x \forall x \in \mathbb R ~$. Prove that the function is injective.
So I understand in order to prove this function is injective, I need to prove that if $~x,~y \in \mathbb R~$,  $~f(x)=f(y)~$ and $~x=y~$.
If someone could please walk me through how to approach a problem like this that would be awesome and really appreciated, my prof doesn't do examples so figuring out the way to go about proving this seems really complicated.
Thank you in advance.

A: Suppose that $f$ is not injective. Then there are distinct real numbers $a$ and $b$ such that $a\neq b$ and $f(a)=f(b)$. But then $(\forall m\in\mathbb N):f_m(a)=f_m(b)$. So, since $a\neq b$, you can't have both $f_m(a)=a$ and $f_m(b)=b$.

A: Suppose $f(x)=f(y)$.  Then $f_z(x)=f_z(y)\,,\forall z$.  In particular,  $x=f_{z_0}(x)=f_{z_0}(y)=y$.  Thus $f$ is injective.


text:
Q: Fatal error: Call to a member function get_tab() on a non-object in D:\wamp\www\relation\application\controllers\c_relation.php on line 7 I got this problem, I researched more but didn't find any solution .
I am creating a Database relation logic For Crud .
Model code is :
<?php

class M_relation extends CI_Model{

public function __construct()
{
    $this->load->database();
    }
    public function get_tab(){
        $query = $this->db->get('user_id');
        return $query->result_array() ;
    }
}

And Controller Code is :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class C_relation extends CI_Controller {

public function index(){
    $this->load->model('m_relation');
    $data['user_id'] = $this->M_relation->get_tab();
    echo var_dump($data['id']);
    $this->load->view('v_relation');
}
public function __construct()
{
    parent::__construct();
    $this->load->model('m_relation');
}

}
?>

Please :)

A: $query = $this->db->get('user');

Instead
$query = $this->db->get('user_id');

The mistake was that i set the get() to user_id its a table field .
instead of table name .

A: please replace
$this->load->model('m_relation');

to
$this->load->model('M_relation');

You load model as m_relation but when you access function using M_relation.


text:
Q: ServiceMix (FuseESB) - Cannot deploy service unit with AggregationStrategy I'm trying to deploy very simple ESB application to Apache ServiceMix (Fuse ESB) and all works fine up to the point where I'm trying to use 'AggregationStrategy' interface. I'm building a proof of concept using EIP and aggregator pattern in particular and cannot deploy my artifact due to NoClassDefFound Error. Looks like a typical class loading issue but I'm out of ideas on how to resolve it. I have tried both: adding and removing camel-core dependency to my service unit (servicemix-camel type).
The basis of the application can be found here. I have modified my routes definition to the following:
public void configure() {
        from("activemq:test2").split(xpath("/notes/note")).parallelProcessing().process(new NoteProcessor()).to("activemq:test3");

        from("activemq:test3").aggregate(header("id"), new MyAggregationStrategy()).completionTimeout(3000).to("activemq:test");
    }

and my custom AggregationStrategy looks like this:
package com.softwarepassion.tutorial.camel;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.processor.aggregate.AggregationStrategy;

public class MyAggregationStrategy implements AggregationStrategy {

    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        Message newIn = newExchange.getIn();
        String oldBody = oldExchange.getIn().getBody(String.class);
        String newBody = newIn.getBody(String.class);
        newIn.setBody(oldBody + newBody);
        return newExchange;
    }
}

I got the following error on plain ServiceMix as well as on FuseESB:

07:50:49,625 | ERROR | use-01-11/deploy | DefaultComponent
  | ?                                   ? | 151 - servicemix-common -
  2011.02.1.fuse-02-11 | Error creating bean with name 'template': Initialization of bean failed; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'camel': Invocation of init method failed;
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name
  'com.softwarepassion.tutorial.camel.MyRouteBuilder': Resolution of
  declared constructors on bean Class
  [com.softwarepassion.tutorial.camel.MyRouteBuilder] from ClassLoader
  [[org.apache.xbean.classloader.JarFileClassLoader:
  name=org.apache.xbean.spring.context.FileSystemXmlApplicationContext@1c4d3b6
  urls=[file:/home/kris/apache-servicemix-4.4.1-fuse-01-11/data/jbi/tutorial-camel-sa/sus/tutorial-camel-su/]
  parents=[[org.apache.xbean.classloader.JarFileClassLoader: name=SU
  parent class loader urls=[] parents=[231.0,
  BundleDelegatingClassLoader for [camel-spring
  (org.apache.camel.camel-spring)], BundleDelegatingClassLoader for
  [camel-cxf (org.apache.camel.camel-cxf)], BundleDelegatingClassLoader
  for [camel-cxf-transport (org.apache.camel.camel-cxf-transport)]]]]]]
  failed; nested exception is java.lang.NoClassDefFoundError:
  org/apache/camel/processor/aggregate/AggregationStrategy 07:50:49,627
  | ERROR | use-01-11/deploy | ServiceAssemblyInstaller         | ?
  ? | 147 - org.apache.servicemix.jbi.deployer - 1.5.1.fuse-01-11 |
  Error deploying SU tutorial-camel-su

A: Do not use JBI its a legacy/dead.
http://gnodet.blogspot.com/2010/12/thoughts-about-servicemix.html
Use the Camel archetypes to create a new OSGi project to be deployed in ServiceMix. The list of archetypes is here
http://camel.apache.org/camel-maven-archetypes.html
For example the camel-archetype-spring-dm or camel-archetype-blueprint

A: For anyone looking for a solution to the above problem, I have finally found here, that I should switch to OSGI type of deployment. You can find working camel-osgi example project inside 'examples' directory at the root of your FuseESB installation.


text:
Q: HashMultiMap save repetitive keys bindings on background? why when table.Count = 1 table iteration functions get more than 1 key-value pairs?
And if this is feature how can I expected behavior?
//
            let table = new HashMultiMap<string, int> (HashIdentity.Structural)
            table.Add("a", 1)
            table.Add("a", 1)
            table.Add("a", 1)
            // now table.Count is one
            let reduced = table.Fold (fun k v acc -> (k,v) :: acc) []
            let acc = ref []
            table.Iterate (fun k v -> acc.contents <- (k,v) :: acc.contents)
            //

reduced and acc.contents contains three ("a",1) pairs

A: The documentation for the Count member says:

The total number of keys in the hash table

If you have multiple values associated with the same key, there is still only a single key, so the value 1 is the expected result for your example. As far as I can see, there is no property that returns the total number of values, but you can implement that easily using Fold:
let valueCount = table.Fold (fun _ _ n -> n + 1) 0


text:
Q: Comma between "because" and a preposition like "in" I have seen this both ways, but is it better to do it like the first or second one? Does it change the meaning of the sentence when the comma is added, or is it just a verbal comma?
1.) That's because, in addition to the troubles here, there were other issues.
2.) That's because in addition to the troubles here, there were other issues.


text:
Q: function representation of power series What is the function representation of this power series?
[Summation from n=0 to infinity of ($x^n)(n+1)!/n!$
The solution is $\frac{1}{(1-x)^-2}$ but how???
I know that $\sum_{n=0}^{\infty}(x^n)/n! = e^x$, but I don't know how to get to the solution from there.

A: Notice that $$\frac{(n+1)!}{n!}x^n=\frac{(n+1)n!}{n!}x^n=(n+1)x^n$$ So, $$\sum_{n=0}^\infty\frac{(n+1)!}{n!}x^n=\sum_{n=0}^\infty (n+1)x^n=\sum_{n=0}^\infty nx^n +\sum_{n=0}^\infty x^n=x\sum_{n=0}^\infty nx^{n-1} +\sum_{n=0}^\infty x^n=$$ $$x \frac d {dx}\Big( \sum_{n=0}^\infty x^n\Big)+\sum_{n=0}^\infty x^n$$
I am sure that you cn take it from here.


text:
Q: Pass e.parameter to array with doPost method Can you pass parameters through DoPost method? I am trying to pass e.parmaters to my array. All I see in return is empty brackets without the value of the parameter I want to push.
Code:
function doPost(e) {
    createProcess(e);
    createStep();
}

function createProcess(e) {
    var app = UiApp.getActiveApplication(); //get the current UI application
    process = [];
    var sheet = SpreadsheetApp.openById("0AuCblud0Ss7BdHA1bXZgmjYXA0liY0IyekhUQm5vWG02MVE").getActiveSheet(    ); //opens spreadsheet
    var row = sheet.getLastRow(); //grabs current row
    process.push(createStep([e.parameter.DivHeadEmail,]));
    process.push(createStep([e.parameter.Director]));
    saveProcess(process,sheet,row);
}

function createStep(approvers) {
    var sheet = SpreadsheetApp.openById("0AuCblud0Ss7BdHA1bXZjYXhkhkA0Y0IyekhUQm5vWG02MVE").getActiveSheet();
    var row = sheet.getLastRow();
    var  step = new Object();
    step['numberOfApprovers'] = approvers.length;
    step['approvers'] = approvers.slice(1);
    step['status'] =  "approved" ;
    return step;
}

A: Yes, you are able to pass parameters to doPost(e) just as you can with doGet(e).
You can check what parameters are being passed to your doPost(e) method by using this inside of it.
var parameters = "";
for (var i in e.parameter) {
  parameters += "e.parameter."+i+" = "+e.parameter[i];
}
Logger.log(parameters);


text:
Q: elasticsearch 5.1 java api DeleteByQuery Elasticsearch version: 5.1.1
OS version: centos 7
Description of the problem including expected versus actual behavior:
ES 5.1 version does not support delete-by-query plugin.
so i need to change the javaAPI code.
The following code is from the previous 2.3 version.
    new DeleteByQueryRequestBuilder(ElasticConnector.getInstance().getJavaClient(), DeleteByQueryAction.INSTANCE)
.setIndices(GLOBAL_ID)
    .setTypes(MessageService.DEVICE)
    .setQuery(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("user_id", user_id))
    .should(QueryBuilders.termQuery("device_id", device_id)
    .mustNot(QueryBuilders.boolQuery()
    .must(QueryBuilders.termQuery("user_id", user_id))
    .must(QueryBuilders.termQuery("device_id", device_id)) ))
    .execute().actionGet();

This code has a problem with

DeleteByQueryRequestBuilder cannot be resolved to a type

How do I change?

A: I think this can solve your problem
BulkIndexByScrollResponse response =
  DeleteByQueryAction.INSTANCE
    .newRequestBuilder(ESClient)
    .filter(yourQuery)
    .source(your index)
    .get();

regards


text:
Q: Android - GCM notifications of app_1 accessible from app_2 I would like to ask you how to get GCM notification from another app. If you know AirDroid or Desktop Notification - these applications somehow (I don't know how) extract notifications (even GCM ones) to desktop.
In my customized app_2 I would like to extract notification from app_1 (but I cannot change app_1, I supposed that app_1 is completed) and these extracted data would be represented for example by text/content of the notification. Is it possible at all? I actually managed this with "normal" notifications but I failed with GCM ones.
I guess that app_1 has a broadcast receiver and a service. I would like to have app_2 that runs on the background and checks GCM notifications by app_1.
I would be satisfied if I have an example code with receiving GCM notification of app_1 with packagename_1. I have not found this specific case on Google if I am not generally wrong.
Thank you.

A: I believe that what you are looking for is NotificationListenerService.


text:
Q: How can I join the frequency of repeated categories to a 'groupby' in Python? [UPDADE]
I am dealing with a large dateset, and now I have reached this part:
agg_diag = ('mean', 'median', 'count')
columns_names_diag = ['ae_diag_mean','ae_diag_median']
df[columns_names_diag].groupby(df['Code']).agg(agg_diag)

Being the output
       ae_diag_mean         ae_diag_median
       mean median count    mean median count
Code
04189  82.0  82.0    1      82.0  82.0  1
07811  14.0  14.0    1      14.0  14.0  1
07812  3.0   3.0     1      3.0   3.0   1
0794   0.0   0.0     2      0.0   0.0   2
0914   4.0   4.0     1      4.0   4.0   1

However, since that "count" is a repetition in both columns in this dataframe, I just want to have one column for it. Count is the quantity of each code that exists in this dataset. So I want an output like this:
       ae_diag_mean  ae_diag_median
       mean median   mean median       count
Code
04189  82.0  82.0    82.0  82.0          1
07811  14.0  14.0    14.0  14.0          1
07812  3.0   3.0     3.0   3.0           1
0794   0.0   0.0     0.0   0.0           2
0914   4.0   4.0     4.0   4.0           1

Anyone can help me? Thank you in advance!


text:
Q: PHP simply wanna echo this week sunday and this week saturday, same for last week i read a lot of long articles and answers but none of this describes this simply, all talk about different variables and many of them give differnt week starting date...
just wanna say
this week
$thissunday= xxxx; (in dd/mm/yyyy)
$thissaturday=yyyy; (in dd/mm/yyyy)

and the previous week
$lastsunday= xxxx; (in dd/mm/yyyy)
$lastsaturday=xxx; (in dd/mm/yyyy)

I tried this
$thisws = strtotime('Sunday this week');
$thiswe = strtotime('Saturday this week');
$lastws = strtotime('Sunday last week');
$lastwe = strtotime('Saturday last week');

and gives long useless number seems timestamp
is it that complicated!?

A: That "useless number" is a UNIX timestamp.
UNIX Timestamp
As the strototime documentation says: "Parse about any English textual datetime description into a Unix timestamp"

A: Use date() function after strtotime() like so:
<?php echo date('d/m/Y', strtotime('Sunday last week'));


text:
Q: apollo federation typescript resolver arguments Hello i have a question related to apollo federation, ive been using apollo server to experiment with graphql and typescript i had everything working but i wanted to move to apollo federation, i had to change the schema building method to buildSubgraphSchema and i am having some troubles with the type definitions of my resolvers.
this is my graphql schema:
import { gql } from 'apollo-server-koa';

const typeDefs = gql`
type State {
  stateId: Int
  name: String
}

extend type Query {
  state(stateId: Int!): State
  stateList: [State]
}

extend type Mutation {
  createState(
    name: String!
  ) : State

  updateState(
    stateId: Int!
    name: String!
  ) : State

  deleteState(
    stateId: Int!
  ) : State
}
`;

export default typeDefs;

this was my resolver in apollo server:
import { PrismaClient } from '@prisma/client';
import { State, UpdateStateInput, DeleteStateInput } from '../types/state';

const prisma = new PrismaClient();

const stateResolver = {
  Query: {
    state: (_params: any, args: { stateId: number }) => {
      return prisma.state.findUnique({
        where: { stateId: args.stateId || undefined },
      });
    },
    stateList: () => {
      return prisma.state.findMany();
    },
  },
  Mutation: {
    createState: (_parent: any, args: State) => {
      return prisma.state.create({ data: { name: args.name } });
    },
    updateState: (_parent: any, args: UpdateStateInput) => {
      const { stateId, ...data } = args;
      return prisma.state.update({ where: { stateId }, data });
    },
    deleteState: (_parent: any, args: DeleteStateInput) => {
      return prisma.state.delete({ where: { stateId: args.stateId } });
    },
  },
  // Relation resolvers
  State: {
    notary: (parent: any) => {
      return prisma.notary.findMany({ where: { stateId: parent?.stateId } });
    },
  },
};

export default stateResolver;

When i pass that resolver to buildSubgraphSchema, typescript shows this error:
Type '{ Query: { state: (_params: any, args: {    stateId: number;}) => Prisma.Prisma__StateClient<State | null>; stateList: () => PrismaPromise<State[]>; }; Mutation: { createState: (_parent: any, args: State) => Prisma.Prisma__StateClient<...>; updateState: (_parent: any, args: UpdateStateInput) => Prisma.Prisma__StateC...' is not assignable to type 'GraphQLResolverMap<any>'.
  Property 'Query' is incompatible with index signature.
    Type '{ state: (_params: any, args: {    stateId: number;}) => Prisma.Prisma__StateClient<State | null>; stateList: () => PrismaPromise<State[]>; }' is not assignable to type 'GraphQLScalarType | { [enumValue: string]: string | number; } | { [fieldName: string]: GraphQLFieldResolver<any, any, { [argName: string]: any; }> | { ...; }; }'.
      Type '{ state: (_params: any, args: {    stateId: number;}) => Prisma.Prisma__StateClient<State | null>; stateList: () => PrismaPromise<State[]>; }' is not assignable to type '{ [fieldName: string]: GraphQLFieldResolver<any, any, { [argName: string]: any; }> | { requires?: string | undefined; resolve: GraphQLFieldResolver<any, any, { [argName: string]: any; }>; }; }'.
        Property 'state' is incompatible with index signature.
          Type '(_params: any, args: {    stateId: number;}) => Prisma.Prisma__StateClient<State | null>' is not assignable to type 'GraphQLFieldResolver<any, any, { [argName: string]: any; }> | { requires?: string | undefined; resolve: GraphQLFieldResolver<any, any, { [argName: string]: any; }>; }'.
            Type '(_params: any, args: {    stateId: number;}) => Prisma.Prisma__StateClient<State | null>' is not assignable to type 'GraphQLFieldResolver<any, any, { [argName: string]: any; }>'.
              Types of parameters 'args' and 'args' are incompatible.
                Property 'stateId' is missing in type '{ [argName: string]: any; }' but required in type '{ stateId: number; }'.

the error gets solved if i set args: any on all the resolver methods. i wanted to know if that is the correct way considering that it loses the type definitions there.
thanks.


text:
Q: Ubuntu 12.04 and 12.10 fails to boot after usb 1-1.4 I'd like to first apologize for my lack of detail in the information as I'm new to Linux and I'd be happy to provide more if you point me in the right direction.
I've tried both 12.04 and 12.10 and both have had issues booting.
In 12.04 I couldn't reboot. A reboot would cause a hang and after the system hanging repeated times, it would start working again. When I would boot up in "regular mode", it would hang at a purple screen. I then tried recover mode which would hang at "fb: conflicting fb hw usage inteldrmfb vs EFI VGA - removing generic driver". I found an article recommending removing "gfxmode $linux_gfx_mode" from the normal boot entry but it wasn't present. Then I removed the quiet splash from the normal boot and found that after "usb 1-1.4: new full-speed USB device number 4 using ehci_hcd" the system would hang. Then I would get "INFO: task swapper/0:1 blocked for more than 120 seconds" with some hex details and a verbose output.
I was advised to upgrade to 12.10 to avoid any potential issues although I wanted to run 12.04 for the LTS side of things. I did a full fresh install of 12.10 and not an upgrade. With 12.10, I have rebooted a few times without issue. I then tried to perform a shutdown which seemed fine until I tried to boot back up and again found I was having issues. The only difference I've found in 12.10 is that now it hangs after the following:
usb 1-1.4: new full-speed USB device number 4 using ehci_hcd
usb 1-1.4: New USB device found, idVendor=0489, idProduct=e042
usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-1.4: Product: BCM20702A0
usb 1-1.4: Manufacturer: Broadcom Corp
And then in hangs again at task swapper.
For HW this is a new Lenovo Z480 and any help you could provide would be well appreciated. Thanks!

A: Okay I just ran into the same problem on my Z580 with Ubuntu 12.04. It rebooted fine a couple of times and then hung up on the purple screen. I had to force restart it again, and now it only shows a blinking cursor. Choosing the recovery boot option hangs up at the exact same place you described.
After some googling it seems like this is a common problem on Z580's recently, and it appears it has something to do with the UEFI boot. Look at the following two threads. Unfortunately, there is no solid solution yet.
Hope this info will help someone more knowledgeable to come up with a solution.
UPDATE:
I managed to solve this issue by booting into the previous Linux kernel 3.2.0-29-generic(the one that came with the 12.04 install disk). To boot using a previous kernel choose "previous linux versions" from the grub boot menu.I later noticed that the problem indeed occur after a kernel update to 3.2.0-35-generric. So it still doesn't boot into the new kernel and hangs as described in the original question. So there for I believe this has something to do with the new 3.2.0-35- kernel.


text:
Q: Company name already taken at github My research-based company's name is already taken on github (mailed the owner without any luck), what is the most recognized naming conventions for company github accounts besides the name directly?
the only ones I found was ibm-dojo and ibm-research

A: Usually, each company has their own naming convention (if any) for projects like that.  For example, IBM has policies in place regarding social media interaction as well as open-source project contributions.
Generally, it's poor form to take the main company name within a repository like GitHub.  In larger organizations, it would be a CLM (career limiting move) for a non-senior employee to take the main name and not be easily accessible.  At IBM, anyone less than a VP claiming the parent name would likely have a short conversation with Legal wherein the relinquish the account credentials.
Assuming the parent company wants its name on the project, then parentCo-subproject is a pretty common naming approach.  Even if the company isn't large enough to sponsor all that many projects, it doesn't hurt to use that pattern anyway.  Projects will come and go, and that makes life easier on future projects (as you're now finding).
Unfortunately, that's not a universal rule and not everyone thinks things through before registering their company on an OSS site.

The above answer pertains mostly to larger companies where the risk of company name collision with other companies is low, but there's a decent risk of project name collision.
Smaller firms may find there is another organization with their name, and it's unlikely that they'll be able to find some sort of arbitration regarding the name's usage (or they might lose in that arbitration).  There are a number of different collision reasons, but all of them generally end up in the 2nd party losing out on the primary name.
At that point, what I have seen is the organization adding some degree of localization to distinguish themselves.  That could be a simple -US or -CA to indicate country, or a .net to show they are foo.net and not foo.com, or they could use the full URL of their main site.
That said, I still think that companyName-project forms a good pattern for the OSS registry.  It creates a subtle shift in the branding of the account as the company is now relying more upon the project brand in order to distinguish that OSS project.


text:
Q: How to know external ip adress of the current pc For example to get local ip address I use:
 string myHost = System.Net.Dns.GetHostName();
 string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[0].ToString();

A: here's a link that may help.  http://www.dreamincode.net/forums/topic/24692-showing-the-external-ip-address-in-c%23/
There's a good post on doing a webrequest to WhatIsMyIP.com


text:
Q: Increasing uGridsToLoad in Fallout: New Vegas What settings can I drop to load more grids without crashing? I can run 9 grids stable but 11 causes the game to crash to desktop. Exterior cell Buffer is at 48 (96=CTD). I want to be able to snipe as far across the map as possible. Perhaps loading low rez buildings and tweaking the LoD? Post me some .ini tweaks please, there is a lot of those LoD and other settings I don't really understand. What settings to drop all the far fake stuff and only load from the real grids?

A: How many uGrids you can load depends on amount of VRAM you have (and RAM possibly), so maybe you hit a wall with 11. To answer your question what settings to tweak, I would say anything that is VRAM extensive, so textures come to my mind first.


text:
Q: How to make my DB stream work when a change occures? I'm trying to insert new message to my Mongodb DB, but the on function doesn't work (should work when stream change occurs) and I get 404 error when I'm using Postman to send the request. What's wrong with the code?
I'm using mongoose 6.7.0
server.js
import express from "express";
import mongoose from "mongoose";
import "dotenv/config";
import Messages from "./messageSchema.js";
import Pusher from "pusher";

// app config
const app = express();
const port = process.env.PORT;

// middleware
app.use(express.json());

//DB config
mongoose.connect(process.env.MONGO_URI);
const db = mongoose.connection;

db.once("open", () => {
  console.log("DB connected");

  const messageCollection = db.collection("MessageModels");
  const stream = messageCollection.watch();
  stream.on("change", (data) => {
    console.log("The change", data);

    if (data.operationType === "insert") {
      const msgContent = data.fullDocument;
      pusher.trigger("messages", "inserted", {
        message: msgContent.message,
        sender: msgContent.sender,
        timestamp: msgContent.timestamp,
        recieved: msgContent.recieved,
      });
    }
  });
});

// API routes
app.get("/", (req, res) => res.status(200).send("Health"));

app.get("/api/messages/all", (req, res) => {
  Messages.find((err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });

  app.post("/api/messages/new", (req, res) => {
    const messageContent = req.body;
    Messages.create(messageContent, (err, data) => {
      if (err) {
        res.status(500).send(err);
      }
      if (data) {
        res.status(201).send(messageContent);
      }
    });
  });
});

// listen to port
app.listen(port, () => console.log(`Listening on port ${port}`));

messageSchema.js
import mongoose from "mongoose";

const messageSchema = new mongoose.Schema({
  message: String,
  sender: String,
  timestamp: String,
  recieved: Boolean,
});

export default mongoose.model("MessageModel", messageSchema);

I tried using onChange function and other similar functions, but it still didn't work.


text:
Q: Time dilation and length contraction for light and how this is interpreted where space is expanding faster than the speed of light First off I am an engineer and not a scientist.  Consequently my course work emphasized classical mechanics and I was never formally introduced to topics like relativity and quantum mechanics in school.
Science is however a fascination of mine so I have been reading and studying on my own in order to try and understand these topics.  I have found the material truly fascinating but do often find it hard to conceptualize the topics.  This is probably what makes it so fun.  I have been thinking about one idea in particular for some time now and haven't found any information that directly discusses it.
By special relativity we learn that the speed of light is constant for all observers in any inertial frame of reference.  For this to be possible Einstein proposed that space and time are essentially one entity and that one observer's space could be another's time (and vice versa).  The relationship is quantified by the Lorenz transformation which shows that as an inertial observer moves arbitrarily close to the speed of light their clocks will tick arbitrarily slow relative to all other inertial observers.  This would indicate that at the limit of the speed of light time actually freezes.  The corollary with space is that it is infinitely contracted.  This gives me the impression that for a photon they experience no time and no space.  So a photon emitted from the surface of the Sun will take just over 8 minutes in the reference frame of an earth observer to arrive at earth but from the perspective of a photon there is no time passage, the distance traveled also being zero.  Fascinating as this idea is it has been a little difficult to swallow since another photon emitted at the same time but in a different direction (say towards Andromeda) would also arrive at its destination instantly and have experienced no measured distance.  I thought I could more or less accept this but then another scenario occurred to me that really seems hard to understand.  We now know that the expansion of the universe is happening in such a way that the distant galaxies are moving away from us at faster than the speed of light.  Or more correctly the space occupied by us and distant galaxies is expanding faster than the speed of light.
So the question is then to consider a photon that is emitted from the surface of the sun and pointed in a direction of space where the nearest object that could absorb the photon is moving away from us faster than the speed of light.  This photon experiences no time and no distance but can still never reach a destination.  This feels paradoxical to me, since there is supposed to be no time passage or space measured the photon's whole existence must be instantaneous, however, there is nothing to absorb it within the causally connected universe along the trajectory that it is travelling. So it would have to experience an infinite amount of time and distance.
Feels like there is something missing in my understanding and I wanted to see if anyone on here could clear this up for me.

A:
So the question is then to consider a photon that is emitted from the surface of the sun and pointed in a direction of space where the nearest object that could absorb the photon is moving away from us faster than the speed of light.

That is why we talk of the "observable universe". Galaxies separating from the observable universe cannot be seen  by us, as the photons leaving those galaxies will never reach us.

The word observable used in this sense does not refer to the capability of modern technology to detect light or other information from an object, or whether there is anything to be detected. It refers to the physical limit created by the speed of light itself.

Your photon example is the reverse coin.

A: Photon has zero rest mass that's why they are able to travel with speed of light.Now why Photons have zero rest mass because a particle gets a mass when it interects with Higgs field. Photons do not interect with Higgs field that's why they have zero rest mass.


text:
Q: Pymongo - removing database tuples that do not have a specific attribute I have a mongodb database. I am currently writing a python script using pymongo to clean the data.
My dataset has an attribute 'country'. I am trying to remove all tuples that's 'country' attribute is not the United States.
I know how to use unset to remove attributes from a database, and I know how to delete an attribute using remove many.
mongo_collection.delete_many({"Country":""})
mongo_collection.update({}, {'$unset': {'Country':1}}, multi=True)

However, I cannot find any resources on how to remove all tuples that do not match a specific attribute value.
Any insight would be greatly appreciated!!!
Thank you!

A: Just pass your condition ($ne --> not equal) to the delete_many
countries_fixtures = [
    {"Country": "FR", "other": "A"},
    {"Country": "US", "other": "B"},
    {"Country": "AT", "other": "C"},
    {"Country": "US", "other": "D"}
]

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.test_stack_088
db.test_stack_088.drop()  # Remove whole collection (to make sure test works)
for country_fixture in countries_fixtures:
    db.test_stack_088.insert_one(country_fixture)
# We should have 4 records in our test_stack_088 collection, right? RIGHT??
assert db.test_stack_088.count() == 4

# Question's answer:
db.test_stack_088.delete_many({"Country": {"$ne": "US"}})  # <---- This
# Yep, the line above is the juicy part...

# Let's make sure, 100% sure it worked...
assert db.test_stack_088.count() == 2
for record in db.test_stack_088.find():
    print(record)

You can take a look to the comparison operators on this link.


text: Q: Error linking .ibd/.frm file into access I have loaded all but one table into access. I am not familiar with .frm or .idb files. When trying to link the table tbl_orderdetails I am getting an error stating that MIR.ORDER is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long. I am guessing MIR.ORDER is a column name but I did not design the table so I am unsure. Is there any way I can open up the tbl_orderdetails.frm or tbl_orderdetails.idb to look for the error and try to correct it?