Q:

NodeJs using Request Promise to call external API, Saving data from the response body

I am currently using a request promise in order to make an API call to the smarty streets API to do address validation. The issue I'm currently stuck on is simply saving the return body of data in order to use it outside the request. What would be the simplest way to save the body in the request to my variable reBody?
Im sure its a simple issue that I'm overthinking so any help would be much appreciated! Attached is the code below as well as the response body itself.
code:
var resBody = null;

request({
    method: 'get',
    uri: url,
    headers: {
        'User-Agent': 'Request-Promise'
    },
    json: true
})
.then(function (body) {
    console.log(body);
    return body
})
.catch(function (err) {
    console.log(err)
});

for (i in resBody){
    console.log(resBody[i].components);
}

response:
[
  {
    input_index: 0,
    candidate_index: 0,
    delivery_line_1: '1 Campus Dr',
    last_line: 'Allendale MI 49401-9401',
    delivery_point_barcode: '494019401017',
    components: {
      primary_number: '1',
      street_name: 'Campus',
      street_suffix: 'Dr',
      city_name: 'Allendale',
      default_city_name: 'Allendale',
      state_abbreviation: 'MI',
      zipcode: '49401',
      plus4_code: '9401',
      delivery_point: '01',
      delivery_point_check_digit: '7'
    },
    metadata: {
      record_type: 'S',
      zip_type: 'Standard',
      county_fips: '26139',
      county_name: 'Ottawa',
      carrier_route: 'R099',
      congressional_district: '02',
      rdi: 'Commercial',
      elot_sequence: '0002',
      elot_sort: 'A',
      latitude: 42.97192,
      longitude: -85.89169,
      precision: 'Zip9',
      time_zone: 'Eastern',
      utc_offset: -5,
      dst: true
    },
    analysis: {
      dpv_match_code: 'Y',
      dpv_footnotes: 'AABB',
      dpv_cmra: 'N',
      dpv_vacant: 'N',
      active: 'Y',
      footnotes: 'N#'
    }
  }
]

A:

You have to move your for loop inside of the then block. Else you can simplify it like this:
let resBody = await request({
  method: 'get',
  uri: url,
  headers: {
    'User-Agent': 'Request-Promise'
  },
  json: true
});

Since it is a promise you can await it. To catch error you can use try..catch block.


Q:

Hide div by clicking another div jQuery

I have a div which when clicked, height changes so that the rest of the content becomes visible.
But I have a button inside this div which I would like to use as a "close-button", to change the height back to it's original value so the content is hidden again, but it's not working.
Here is the code:

$('.scrollClick').click(function() {
  $(this).css("height", "350px");
});
$('.acceptCta').click(function() {
  $('.scrollClick').css("height", "27px");
});
.scrollClick{
  font-family:inherit;
  background-color: #000E52;
  color: #fff;
  text-align: center;
  display: inline-block;
  position: fixed;
  z-index: 9999;
  cursor: pointer;
  right: 20px;
  padding: 5px;
  border-radius: 5px;
  box-shadow: 2px 2px 2px rgba(0,0,0,0.4);
  transition: all 0.5s ease;
  font-size: 16px;
  max-width: 240px;
  box-sizing: border-box;
  text-align: center;
  height: 27px;
  overflow: hidden;
}

.dropContentBox{
  display: inline-block;
  color: #fff;
  transition: all 0.5s ease;
  text-align: center;
}

.acceptCta{
  display: inline-block;
  position: relative;
  background-color: #7CBD2B;
  color: #333;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 25px;
  box-sizing: border-box;
  border-radius: 3px;
  box-shadow: 2px 2px 2px rgba(0,0,0,0.15);
  transition: all 0.5s ease;
  z-index:10;
}
.acceptCta:hover{
  background-color: #88D41B;
}
.acceptCta:hover .arrow{
  opacity: 1.0;
}

.arrow {
  border: solid #333;
  border-width: 0 3px 3px 0;
  display: inline-block;
  opacity: 0;
  padding: 3px;
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  transition: all 0.5s ease;
}

.bouncer {
  position: relative;
  border: solid #fff;
  border-width: 0 3px 3px 0;
  display: inline-block;
  padding: 3px;
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transition: border-color 0.5s ease;
  animation: bouncer 2s infinite;

}

@keyframes bouncer {
  0% {
    bottom: 0px;
  }

  20% {
    bottom: 7px;
  }

  40% {
    bottom: 0px;
  }

  60% {
    bottom: 7px;
  }

  80% {
    bottom: 0px;
  }

  100% {
    bottom: 0px;
  }
}

  Viktig informasjon! Les her

Jeg har lest og forstått

So as you see in my jQuery code, I want the .scrollClick class to go back to it' original height, when clicking the .acceptCta div.
What am I doing wrong? Ty

A:

The problem is that the click on your second button also triggers a click on your first button as the second button is within the first button. you can restructure your html or can stop propagation.
$('.scrollClick').click(function() {
  $(this).css("height", "350px");
});
$('.acceptCta').click(function(e) {
  e.stopPropagation();
  $('.scrollClick').css("height", "27px");
});


Q:

Infinite Jumper Snow Effect

I wish to achieve a snowing effect on my game. The game is made in LibGDX and im using ParticleEmitter. I created a snow effect in ParticleEditor which consists in a line which spawns snow flakes. The problem is:
First, and the most important, since the game movement is vertical (its a jumper), if i just place the line above the screen, the jumping makes it look unnatural since when im jumping up, and the camera follows me, the particle emitter also has to move up, and the snow flakes are spawned with a bigger vertical distance; And when Im going down from the jump, a section of closer snowflakes is spawned due to that occurence. That makes the snow visually inconsistent.
Second, i wanted the snow to show up filling the screen from the start, instead of it starting to follow when the emitter is started.
To try to fix the first problem, i made the snow screen static, but it looks horrible, i really want the feeling that the snow is falling and my character is going up against it.
Any ideas how to achieve such an effect?

A:

Another option would be to spawn a fixed number of snow particles and make them teleport to the top when they reach the bottom of the screen. This is trivial but in your case it should work fine.


Q:

How to extract multiline text using regex python

Hi I have the following text.

x = """Hello, this is a\nmultiline text\nend.Hello, this is\nthe second
  chunck\nend."""

This pattern of Hello,  \nend. keeps on repeating. I want to extract the text between each set of these two words. I tried using this

b=re.search(r'(?<=Hello,).+(?=end)', x, re.DOTALL)

but I get all the text from the start to the end. How do I get the separate chunks of text?
Thanks.p

A:

Use a lazy quantifier: .+? instead of .+.
The problem is that the .+ matches as far as it can, so just eats all the way to the end of the documents. Adding the question mark tells it to match as little as it can.


Q:

update query with 1.5 million rows taking long time to execute mysql

I have two tables namely tableA with columns object & freq with 45000 rows and tableB having column object with 1.5 millions rows. I am trying to update freq column for tableB by using below query but its taking nearly about 30 minutes to execute.
UPDATE tableB JOIN tableA ON tableB.object= tableA.object
SET tableB.freq= tableA.freq

Is there anyway to reduce the time as I need to do it for multiple iterations.

A:

I added indexes and its very quick to execute now.. Thanks :)


Q:

WPF interop - HwndHost not automatically destroying the hosted window

I am having trouble ensuring a hosted window is correctly destroyed.
I have a HwndHost-derived class that I am displaying in a TabControl (though that is probably irrelevant).  I am trying to destroy the hosted content when the tab closes (not when the containing window closes.)
I currently have code to the effect of myControlHost.Dispose(), which ensures that HwndHost.DestroyWindowCore is called immediately.  The problem is, DestroyWindowCore does not actually destroy the hosted HWND content!
I would have thought that this was enough to ensure that the underlying CWnd-derived application receives a WM_CLOSE or something, but this does not seem to happen - Spy++ reports only a registered message "HwndSubclass.DetachMessage" being sent.
I have read that you are not supposed to explicitly send your hosted window a WM_CLOSE in the DestroyWindowCore, as this is supposed to happen automatically.
What is the correct way to ensure a hosted window is correctly destroyed when manually removing a HwndHost-derived control?

A:

According to this MSDN document, they are calling DestroyWindow() in DestroyWindowCore:
http://msdn.microsoft.com/en-us/library/ms752055.aspx
DestroyWindow() will post WM_CLOSE message into message queue, so actually you don't need or should not directly send/post WM_CLOSE.
In my application, actually I am calling DestroyWindow() in a sub DLL which is called from C# side in DestroyWindowCore callback.  Then, everything is working fine.


Q:

Passing addrinfo structure from child to parent using shared memory

I wanted to pass output of getaddrinfo structure (*res) into parent (from child) process using shared memory as below
pid = fork();
if (pid == 0)
{
    .....
    iStatus = getaddrinfo(argv[1], NULL, &hints, &servinfoC);
    ...
    shmid = shmget(GETADDR_SHM_KEY, SHMSZ, IPC_CREAT | 0666);
    ....
    shmC = shmat(shmid, (void*)NULL, 0));
    memcpy(shmC, servinfoC, sizeof(struct addrinfo));
    freeaddrinfo (servinfoC);
}
else
{
    struct addrinfo *servinfoP;
    while ((pid = waitpid (pid, &status, WUNTRACED | WCONTINUED)) > 0)
    shmid = shmget(GETADDR_SHM_KEY, SHMSZ, 0666 | IPC_CREAT);
    shmP = shmat(shmid, (void*)NULL, 0));

    /*HELP Copy shmP to servinfoP struct*/

}

I tried memcpy but it didnt helped because of memory allocation required for addrinfo.
Thank you in advance for your time and help
Regards
Manoj

A:

This will not work. The addrinfo struct contains pointers to other memory regions, and on top of that is a linked list of results. You will need to flatten it if you want to pass it though shared memory.
Eg:
struct addrinfo_flat
{
    int ai_family;
    int ai_socktype;
    int ai_protocol;
    struct sockaddr_storage ai_addr;
    socklen_t ai_addrlen;
};

struct addrinfo_flags *addrs = (struct addrinfo_flat*)shmC;
addrs->ai_family = ai->ai_family;
addrs->ai_socktype = ai->ai_socktype;
addrs->ai_protocol = ai->ai_protocol;
memcpy(&addrs->ai_addr, ai->ai_addr, ai->ai_addrlen);
addrs->ai_addrlen = ai->ai_addrlen;

(multiple results left as an exercise)

A:

It sounds to me like you're trying to implement asynchronous DNS lookups with fork/processes, which is a really really bad idea. If you don't want an async DNS library, just use threads instead of fork. Then the resulting struct addrinfo is already in your program's address space and it can be used (and freed) by the caller.
The new thread should call getaddrinfo and inform the caller when it finishes; the method you use to inform the caller should depend on how your program's event handling works. Assuming it's single-threaded, you're probably using select/poll (or an abstraction thereof like libevent) so it may make sense for the thread to use a pipe that you can select on to indicate when the lookup is done.
P.S. Never use shmget etc. except for legacy interfaces (like X11) that require it. There are much cleaner more modern ways to do shared memory like mmap with MAP_SHARED|MAP_ANONYMOUS (for anonymous shared memory that you'll only share with your forked children) or shm_open (POSIX named shared memory) or even mmap of ordinary files...


Q:

GitLab CI, monorepo and feature branch

I have a monorepo in GitLab with a Feature Branch approach.
What I'm trying to achieve is to launch the part of the pipeline associated to the directory containing the altered files. So my .gitlab-ci.yml looks like :
job1:
  stage: build
  script:
    - ...
  only:
    changes:
      - myparentdir/dir1/*

job2:
  stage: build
  script:
    - ...
  only:
    changes:
      - myparentdir/dir2/*

Create a new branch from develop
Commit myparentdir/dir2/test.txt on this branch
The pipeline launch every build jobs !

It seems like GitLab is considering every files as altered when working with a new feature branch.
Do you know any workaround?

A:

Gitlab ci always treats changes for new branches as true. The reason is that they can't decide what to compare against.

what this means is that for the first pipeline of a new branch, everything will be built.

See the feature request for more details.
But, there is a fairly new feature called Pipelines for merge requests - that runs a stage on merge requests. Here is the feature request that implements changes with merge_requests. It's merged, but I'm not sure if it's already released. (the milestone is 11.9 - the next release)
In the meantime you can implement it yourself - You can add a stage that compares the changes (git diff) and decides whether to run the next stage:
.store_diff_from_main: &store_diff_from_main |
  git diff --name-only origin/master...HEAD > "${DIFF_FILE}"
  git diff --name-only HEAD~1 >> "${DIFF_FILE}"

.skip_stage: &skip_stage_condition |
  echo Checking for changes in ${STAGE_PATHS}, changed files
  # https://coderwall.com/p/gecfwa/git-diff-vs
  cat .diff-from-master
  # also cover merge squash cases
  if ! (cat ${DIFF_FILE} | grep -E "${STAGE_PATHS}"); then
    echo "Skipping stage ..."
    exit 0
  fi


Q:

PhD Applications: Can a good academic record in my master's compensate for a horrible UG academic record?

I have a very bad undergraduate academic record -- I failed or didn't attend the end semester exams for many courses (15 courses, to be exact!), and I  had to clear these later on, towards the end of my course.
Admissions to graduate courses in my country (India) are based on entrance examinations (and not your profile or UG record) -- which I've cleared and I'll be going to one of the best universities in my country.
I wish to do a PhD, and I want to keep options in the US or UK open. I intend to study well in my masters and get good scores, and, going by what I've done in the past couple of years, I think I'll be a lot more disciplined in my masters.
My only worry is: will my undergraduate record be a bottleneck no matter how hard I try in my masters? Should I just go into the industry after my masters? I really want to do a PhD!
My overall undergrad GPA is bad (2.72), with, as I've said, 15 "backlogs" (exams that I didn't attend or failed, and cleared later on). However, during the last 3 semesters, I took no backlogs and I averaged above 3. During the final two semesters, I averaged 3.2 and in the final semester I got a 3.4.

A:

In short:
You need to do some research-type work during your Master's to evaluate if your desire to get a Ph.D. has some foundation.
You certainly would have a chance to get into a Ph.D. program with strong enough application. However, you would have to work hard during your Master's.

There are several things you need to consider:

you have not yet finished (or, I guess, even started) your Master's degree. Therefore, you are planning way ahead.
you certainly want to do a research-based Master's degree with a thesis, as opposed to doing a pure course-based Master's. Doing research during your Master's would allow you to understand if you like doing research in the first place. Also, it would strengthen your potential application for a Ph.D.
a carefully written Letter of Intent would be crucial.
sometimes, only a GPA in your last two years of the undergraduate program is used for applicants with a Master's degree.
you should make a decision of industry vs academia closer to the time you are finishing your Master's degree. Moreover, even if you get into industry, nothing prevents you from applying to a Ph.D. program several years later if you still have research interests and, especially, if you position at industry had a research component that you were excited about.


Q:

Reaction forces acting on a ladder against a wall

I've seen some problems that talk about a ladder leaning against a frictionless wall, with a person standing on it. The ladder doesn't move(net force = 0). The problem is, I don't know what directions the reactions forces(that is, the force of the wall on the ladder, and of the floor on the ladder) should have. I've seen it solved like this:

where the force of the wall on the ladder is horizontal, and the force of the floor on the wall is vertical, and also in this way:

where the normal force of the wall is said to have both y and x components.
EDIT: this is a drawing of the forces acting on the ladder. The original image of the situation is

I didn't notice it was leaning against over a corner (and I also wouldn't have thought it would make a difference)
I don't know which interpretation to believe. Is the force of the wall always perpendicular to the wall itself? Or it can it have y and x components?

A:

Those are different situations.
In the first case, the ladder is leaning against a vertical wall.  (it's not shown in your picture, but implied).  The wall would then provide a normal force only in the horizontal direction.
In the second case, the ladder is leaning over a corner.  In that case, the contact has a normal force based on the angle that the ladder comes into contact with the corner.
Without friction, the reaction force is always perpendicular to the contact surface, which is different in each situation.


Q:

How to select certain columns by multiple conditions?

I've made a dataframe from a dictionary to manipulate it.
dic_people = defaultdict(dict)

dic_people['A']['language']    = 'English'
dic_people['A']['nationality'] = 'Russia'
dic_people['A']['joined']      = 201010

dic_people['B']['language']    = 'French'
dic_people['B']['nationality'] = 'Canada'
dic_people['B']['joined']      = 201009

dic_people['C']['language']    = 'English'
dic_people['C']['nationality'] = 'Canada'
dic_people['C']['joined']      = 201008

dic_people['D']['language']    = 'French'
dic_people['D']['nationality'] = 'France'
dic_people['D']['joined']      = 201007

dic_people['E']['language']    = 'English'
dic_people['E']['nationality'] = 'Ireland'
dic_people['E']['joined']      = 201011

df = pd.DataFrame.from_dict(dic_people)

>>> df
                A       B        C       D        E
joined        201010  201009   201008  201007   201011
language     English  French  English  French  English
nationality   Russia  Canada   Canada  France  Ireland

I want to select 2 people who 1) joined earliest and 2) speak English. So, the result will be
                A       C
joined        201010  201008
language     English  English
nationality   Russia  Canada

I'd like to know how to do this. I tried df[ df.loc['language'] == 'English'], but it seems it's somewhat different when referring to rows, not columns.

A:

Use DataFrame.loc for filter by rows and for first 2 column select by positions by DataFrame.iloc:
#if necessary sorting by 'joined' value in index
#df = df.sort_values('joined', axis=1)

df1 = df.loc[:,  df.loc['language'] == 'English'].iloc[:, :2]
print (df1)
                   A        C
language     English  English
nationality   Russia   Canada
joined        201010   201008


Q:

Accessing Input Layer data in Tensorflow/Keras

I am trying to replicate a neural network for depth estimation. The original authors have taken a pre-trained network and added between the fully connected layer and the convolutional layer a 'Superpixel Pooling Layer'. In this layer, the convolutional feature maps are upsampled and the features per superpixel are averaged.
My problem is that in order to successfully achieve this, I need to calculate the superpixels per image. How can I access the data being used by keras/tensorflow during batch processing to perform SLIC oversegmentation?
I considered splitting the tasks and working by pieces i.e. feed the images into the convolutional network. Process the outputs separately and then feed them into a fully connected layer. However, this makes further training of the network impossible.

A:

At the time it seems to be impossible to actually access the data within the symbolic tensor. It also seems unlikely that such functionality will be added in the future since in the Tensorflow page it says:

A Tensor object is a symbolic handle to the result of an operation, but
  does not actually hold the values of the operation's output.

Keras allows for the creation of personalized layers. However, these are limited by the available backend operations. As such, it is simply not possible to access the batch data.


Q:

Sybase: How to string multiple T-SQL commands together

I want to execute the following commands in a single DataAdapter command:
SET ROWCOUNT 10; SELECT * FROM dbo.SYB_CO_COLOUR ;SET ROWCOUNT 0
but this isn't accepted by my Sybase DB, not even in the Interactive SQL tools that ships with the DB.
I have not changed the command_delimiter from the semi-colon default so I am surprised that I get the error
Incorrect Syntax near ';'
What am I missing?
Thanks

A:

Remove semicolon and seperate them by space like:
SET ROWCOUNT 10 SELECT * FROM dbo.SYB_CO_COLOUR SET ROWCOUNT 0

It outputs 10 rows and resets rowcount back.


Q:

how to set and update a database filed to random numbers

hello i have a table where data is stored, this table consist of a field called tnx_ref, i am trying to automatically update this field with random numbers anytime i update my table
this is what i tried,
$tnx_ref = $_SESSION['genref'];

$sql = "UPDATE transactions ".
      "SET tnx_ref = '62323232'".
    "WHERE id = $id";

from the snippet above i have updated the value of that particular field "tnx_ref with "62323232", but now i want to make it different random numbers for every time i update.
how can i possible do this, any1 done such

A:

So, you can dou it using mysql
(for generating 2-digit random numbers between 10 and 99 for example):
$sql = "UPDATE transactions ".
      "SET tnx_ref = FLOOR(10 + (RAND() * 90))".
    "WHERE id = $id";


Q:

Can't extract data with getJSON

Im doing the freecampcode curriculum right now i'm at the local weatherapp.
My problem here is everytime i try to use, i get apiLink is not defined. I understand that the .getJSON part can't connect with the var defined inside the definedCordinates function.
Also i tried to use the direct api link on the .getJSON function, but even with that i get 0 input from json, im using console.log(data) and $("#temp").text to check the input from json.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>My Local Weather App</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="custom.css">.

My Local Weather App

icon

temp

 city name

 sky

 wind

 Powered by openweathermap.org API

 button celsius or farh

A:

The issue is because your apiLink variable is defined in the definedCordinates() function, which is well out of scope of the document.ready handler.
To fix this you need to restructure your logic so that the apiLink is available to the AJAX request by using the appropriate callbacks on async methods. Try this:
$(document).ready(function(){
    getCordinates(function(apiLink) {
        $.getJSON(apiLink, function(data) {
            console.log(data);
        })
    });
})

function getCordinates(callback) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = Math.floor(position.coords.latitude);
        var longitude = Math.floor(position.coords.longitude);
        var apiLink = "https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=##########"
        callback && callback(apiLink)
    });
}

Also note that the apiLink should be an absolute URL, ie. it needs a http:// or https:// prefix.


Q:

Processing C command line arguments

How do I process multiple command line arguments like say in a package manager? I am giving a shot at writing a package manager and right now accepting the packages to install is giving me quite the headache. For example the user wants to install package x,y and z. Right now my code will send 3 different requests to a function. I would like to get all the package names in one go. So for example, the user wants to install package x,y and z, it would be processed and my code will send a request to a function stating that it needs x,y and z and the function will begin work immediately.
Here's my current implementation...
case 'S':
    switch (argv[1][2]) {
        case 'u':
            id = 1;
            alfred("system", "update", "", id);
            break;

        case 'r':
            id = 1;
            alfred("system", "reload", "", id);
            break;

        case 'i':
            if (argc - 2 != 0) {
                // Loop until packages are complete.
                packages = 2; // Starting point of packages = argv[2][0]
                srand(time(NULL)); // Seed for random number
                id = rand(); // Generate random number for id
                argc = argc - 2 + 1; // argc minus the number of packages and plus 1
                /* This is a very inefficent loop! */
                /* Must get all targets and feed it to alfred */
                while (packages <= argc) {
                    alfred("system", "install", &argv[packages][0], id);
                    packages++;
                }
            } else {
                printf("Unrecognized format. Execute alfred -h for more information.\n");
            }
            break;

        default:
            printf("Unrecognized format. Execute alfred -h for more information.\n");
            break;
    }
    break;

A:

You can also try libargtable.
I used it before to parse various arguments, it's very handy.


Q:

after writing a files to an ext4 volume do I need to do more than flush to guarantee the file is fully written?

I've written some code where its very important that beyond a certain point that the contents of a file are written to disk
I'm using ext4, such that the volumes integrity is guaranteed with the journal
in order to guarantee my file is actually on disk and not vulnerable to errors replaying the journal in the event of a crash, do I need to do anything more than flush()?   I believe that's it, that the contract of flush is that the contents are on disk, and all buffers/caches are flushed

A:

flush() ensures that all processes see the file in the same state, but does not guarantee that all bytes have been written to disk. A further call to fsync() or fdatasync() is required.


Q:

Cannot update table by counting fields in related table

I'd like to update followers in profile table by counting the followed_id on follow table.
mysql> explain follow;
+-------------+---------+------+-----+---------+-------+
| Field       | Type    | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| id          | int(11) | NO   |     | NULL    |       |
| followed_id | int(11) | NO   |     | NULL    |       |
| follower_id | int(11) | NO   |     | NULL    |       |
+-------------+---------+------+-----+---------+-------+

And
mysql> explain profile;
+----------------+---------------+------+-----+-------------------+----------------+
| Field          | Type          | Null | Key | Default           | Extra          |
+----------------+---------------+------+-----+-------------------+----------------+
| id             | int(11)       | NO   | PRI | NULL              | auto_increment |
| user_id        | int(10)       | NO   | MUL | 0                 |                |

| followers      | int(7)        | NO   |     | 0                 |                |
| following      | int(7)        | NO   |     | 0                 |                |
+----------------+---------------+------+-----+-------------------+----------------+

Here is the query that I came up with:
UPDATE profile A
INNER JOIN (SELECT id,COUNT(*) idcount FROM follow  GROUP BY id) as B
  ON B.id = A.user_id
SET A.followers = B.idcount

But the query does not work as it should. It adds only 1 when profile has followers.
How can I fix this?

A:

You are currently counting the number of rows for each id value in follow, which is always going to be 1. What you need to do is count the number of follower_id values for each followed_id. Also, as @juergend pointed out, you should use a LEFT JOIN so that you can get 0 values for users with no followers. Change your query to this:
UPDATE profile A
LEFT JOIN (SELECT followed_id, COUNT(DISTINCT follower_id) AS idcount
           FROM follow
           GROUP BY followed_id) as B ON B.followed_id = A.user_id
SET A.followers = COALESCE(B.idcount, 0)

You can use a similar query to update following:
UPDATE profile A
LEFT JOIN (SELECT follower_id, COUNT(DISTINCT followed_id) AS idcount
           FROM follow
           GROUP BY follower_id) as B ON B.follower_id = A.user_id
SET A.following = COALESCE(B.idcount, 0)


Q:

Filter elements in a DataGridView

I should only take some items.
Take groups that do not contain Z4TC in the Model tag
The excel file schema is as follows
<ConfigRegolatori>
<Id>6</Id>
<Address>92</Address>
<Category>90</Category>
<Mode>TC_K</Mode>
<Model>Z4TC</Model>
<Name>KT6</Name>
<Port>COM1</Port>
<Channel>2</Channel>
<LowerEndScale>0</LowerEndScale>
<UpperEndScale>400</UpperEndScale>
<NegativeGradient>10</NegativeGradient>
<PositiveGradient>10</PositiveGradient>
<PercX10>false</PercX10>

<ConfigRegolatori>
<Id>7</Id>
<Address>7</Address>
<Category>100</Category>
<Mode>TC_K</Mode>
<Model>M9_Servo</Model>
<Name>KT7</Name>
<Port>COM1</Port>
<Channel />
<LowerEndScale>0</LowerEndScale>
<UpperEndScale>400</UpperEndScale>
<NegativeGradient>10</NegativeGradient>
<PositiveGradient>10</PositiveGradient>
<PercX10>false</PercX10>

The code part is the following
dtConfReg = new DataTable();
                dtConfReg.ReadXml(Principale.strPathConfig + "\\ConfigRegulators.xml");
                dtConfReg.TableName = "ConfigReg";

bsouReg = new BindingSource();
                bsouReg.DataSource = dtConfReg;
                dgvwConfigReg.DataSource = bsouReg;

Thanks

A:

You can set the Filter property on the BindingSource:
bsouReg = new BindingSource();
bsouReg.DataSource = dtConfReg;
bsouReg.Filter = "Model <> 'Z4TC'";
dgvwConfigReg.DataSource = bsouReg;

The documentation for the filter expression can be found here.


Q:

How to load json.el included in emacs instead of fallback lib included in gnus

I want to use the json.el included in 24.5, but cannot do that, because gnus includes an older version of json.el that is loaded before the one from 24.5.
When running list-load-path-shadows I got this as one of the shadows:
/usr/share/emacs/site-lisp/gnus/gnus-fallback-lib/json hides /usr/share/emacs/24.5/lisp/json
How do I prevent the fallback json from being loaded?

A:

You can re-add /usr/share/emacs/24.5/lisp/ to the start of the load-path by doing something like this
(push "/usr/share/emacs/24.5/lisp" load-path)

While this will work, this is system/installation dependent, I found one installation independent way to get path to lisp startup.el
(expand-file-name "../lisp" data-directory)

Combining these together the following should solve your issue
(push (expand-file-name "../lisp" data-directory) load-path)

Please note that this works because gnus packaged with emacs is installed in /usr/share/emacs/24.5/lisp/gnus directory had it been installed directory in /usr/share/emacs/24.5/lisp, the above would have shadowed the package you installed from your package manager.


Q:

Shell - Syntax error in expression (error token is "16")

I am doing a project for my university, and this is the first time I'm coding using Bash.
I am trying to go trough a .txt document, reading every line, and taking the information I need to make a sum.
The .txt document looks something like this:

83210:Henrique Gaspar:EIB2:911235444:metas@gmail.com:carro:BMW:82-RX-14:5:25:26
  88110:Vasco Rapido:IB2:962222222:vrapid@gmail.com:mota:BMW:33-MT-99:3:5:16
  88020:Maria Aguiar:EIB2:911555444:mguiar@gmail.com:carro:mercedes:88-TX-11:2:20:12

And for what I am doing I need to make the total sum of last number of each user, so 26+16+12.
Now, here is my code:
#!/bin/bash
echo -n "Nº de condutores: "
echo $(cat condutores.txt | wc -l)
echo -n "Nº de passageiros: "
echo $(cat passageiros.txt | wc -l)
echo -n "Saldo total dos condutores: "
x=0
linhas=$(cat condutores.txt | wc -l)
i=0
while [[ $i -le $linhas ]]; do
    sum=$(cat condutores.txt | head -$i | tail -$(( $linhas + 1 - $i )) | cut -d':' -f11)
    x=$((x+sum))
    i=$((i+1))
done
echo "$x"

I wrote it in full here so nothing gets missed out.
What matters for the problem here is from line 7 to 15.
I don't know if it is the way I am going through each line of the condutores.txt file or any other thing. But I am getting this error:
Saldo total dos condutores: ./stats.sh: line 12: 26
16: syntax error in expression (error token is "16")
26

So for some reason it only reads the first and second line of the .txt document, but can't make the sum, can anyone help me here please?
Thanks in advance.

A:

Your $sum contains more than one line, so it cannot be interpreted as number. And your text processing loop is a nightmare, there is a more cleaner solution. Look:
x=0
while IFS=: read -r a b c d e f g h i j k; do
    x=$((x+k))
done < condutores.txt
echo "$x"


Q:

Python MemoryError when storing saved lists

I am new to python, so I apologize if this example is trivial.
I am trying to write a simple script that will pase and extract parts of two large datafiles (~40gb each) into one resulting file with a slightly altered format. I originally tried to use readlines(), but that reads all of the files into memory, and our instance only has 28gb of memory. Using the sizehint parameter only parses a portion of the file.
I am now iterating over the file. The problem is that I store the output of the text parsing in three lists that  grow to be rather large, eclipsing the available memory. I thought this would just switch to using the swap, which would be fine, but it instead just exits with a "MemoryError".
This works fine with small sample files, but chokes on our actual data.
The script:
import sys

a = []
b = []
c = []

file1 = open(sys.argv[1],"r")
for line in file1:
    if '@' in line:
        a.append(line.lstrip('@').rstrip('\n'))
        b.append(file1.next().rstrip('\n'))
file1.close()

file2 = open(sys.argv[2],"r")
for line in file2:
    if '@' in line:
        c.append(file2.next().rstrip('\n'))
file2.close()

file3 = open(sys.argv[3],"w")
for i in xrange(len(a)):
    file3.write("".join([">",a[i],'\n',b[i],":",c[i],"\n"]))

What I have found online suggests creating some sort of database to store the variables, but that shouldn't be required. Do you have any ideas how I should deal with this?
For completeness, this is what I'm trying to do (from our example test-data:
file1:

@Read.Salmonella_paratyphi_A_chromosome.29004.4835/1
TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACKIPPTCGTAG
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

file2:

@Read.Salmonella_paratyphi_A_chromosome.29004.4835/1
TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACAAACGATTCT
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

file3 (output):

>Read.Salmonella_paratyphi_A_chromosome.29004.4835/1
TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACKIPPTCGTAG:TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACAAACGATTCT

A:

I haven't tried this myself, but it seems like the following should work:
file1 = open(sys.argv[1],"r")
file2 = open(sys.argv[2],"r")
file3 = open(sys.argv[3],"w")

for line1 in file1:
    if '@' in line1:  # line1.startswith('@') is probably better here
        a=line1.lstrip('@').rstrip('\n')
        b=file1.next().rstrip('\n')
        for line2 in file2:
            if '@' in line2:
                c=file2.next().rstrip('\n')
                break
        file3.write(">%s\n%s:%s\n"%(a,b,c))

file1.close()
file2.close()
file3.close()

In this case, you're only keeping one line in memory at a time for each file...which should be fine unless the files have really long lines ;^).
Also, since you're lstriping the '@' character, you might want to consider using if line.startswith('@') instead of if '@' in line.


Q:

loading another nib into a viewController

I have a ViewController that includes its own .nib file, I am wanting to load another .nib into this ViewController that will be a menu of sorts... however I am just not sure how to do this and was hoping for some help.
Before I show you the code I will explaine what I have done.

I have a UIViewController with a Nib that is my main view.
I have created another nib which is going to be a menu that appears as a subview to the main view
I have changed this nibs class to the UIViewController of the main view so that it can see all of the same IBActions and outlets.
I have then run the code below trying to load the seperate nib as a subview however when I run it the subview of the other nib is not showing up....
    jumpBarPortraitNib = [[UIView alloc] initWithFrame:CGRectMake(0.0, 50.0, 320.0, 367.0)];

    // add jumpbar container to view
    [self.view insertSubview:jumpBarPortraitNib belowSubview:actionTabBar];

A:

There's clearly some confusion here.
A nib is merely an archive that contains(*) objects, including (usually) one or more view objects (UIView in your case).  You don't "load a nib as a subview."  You instantiate the nib, potentially handing it to a UIViewController to own and manage it, and add a view referenced within the nib to your view hierarchy.
All you have done with your first line of code is create a generic UIView instance with a given frame size and insert it into whatever [self view] is.  There is nothing in what you wrote that actually references a nib, even though you misnamed your view as a nib.
For what you are doing, I would probably go one of two routes:

Add the view as a separate top-level view in your original nib, and connect it to an IBOutlet.  You can then display the menu easily from within the common UIViewController instance you have set as the nib's File Owner.
Have a separate UIViewController instance that will just manage the menu view, and which you will use to instantiate the nib's contents using -initWithNibName: as @Aaron mentioned.  (Note that you shouldn't need to set the frame externally; the frame will be archived in the nib as a property of the view.)

*: Not really, but you can think of it this way.


Q:

Выбор извлекаемых виртуальных машин

Требуется на хост-машине Windows развернуть несколько виртуальных. Они сохранены в одном файле VBox.ova (включая образы дисков и конфигурацию). В файле содержится 6 виртуальных машин. Ниже приведена конфигурация.

Disks:  vmdisk1   5762867200  -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk1.vmdk -1  -1
vmdisk2   14298431488 -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk2.vmdk -1  -1
vmdisk3   16106127360 -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk3.vmdk -1  -1
vmdisk4   5368709120  -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk4.vmdk -1  -1
vmdisk5   10737418240 -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk5.vmdk -1  -1
vmdisk6   26843545600 -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk6.vmdk -1  -1
vmdisk7   10737418240 -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk7.vmdk -1  -1
vmdisk8   16106127360 -1  http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized   VBox-disk8.vmdk -1  -1
Virtual system 0:
 0: Suggested OS type: "DOS"
    (change with "--vsys 0 --ostype <type>"; use "list ostypes" to list all possible values)
 1: Suggested VM name "DOS"
    (change with "--vsys 0 --vmname <name>")
 2: Number of CPUs: 1
    (change with "--vsys 0 --cpus <n>")
 3: Guest memory: 353 MB
    (change with "--vsys 0 --memory <MB>")
 4: Sound card (appliance expects "", can change on import)
    (disable with "--vsys 0 --unit 4 --ignore")
 5: USB controller
    (disable with "--vsys 0 --unit 5 --ignore")
 6: Network adapter: orig NAT, config 2, extra slot=0;type=NAT
 7: Floppy
    (disable with "--vsys 0 --unit 7 --ignore")
 8: CD-ROM
    (disable with "--vsys 0 --unit 8 --ignore")
 9: IDE controller, type PIIX4
    (disable with "--vsys 0 --unit 9 --ignore")
10: IDE controller, type PIIX4
    (disable with "--vsys 0 --unit 10 --ignore")
11: Hard disk image: source image=VBox-disk1.vmdk, target path=D:\VBox\DOS\VBox-disk1.vmdk, controller=9;channel=0
    (change target path with "--vsys 0 --unit 11 --disk path";
    disable with "--vsys 0 --unit 11 --ignore")
Virtual system 1:
 0: Suggested OS type: "Linux"
    (change with "--vsys 1 --ostype <type>"; use "list ostypes" to list all possible values)
 1: Suggested VM name "Gentoo"
    (change with "--vsys 1 --vmname <name>")
 2: Number of CPUs: 2
    (change with "--vsys 1 --cpus <n>")
 3: Guest memory: 3260 MB
    (change with "--vsys 1 --memory <MB>")
 4: Sound card (appliance expects "", can change on import)
    (disable with "--vsys 1 --unit 4 --ignore")
 5: USB controller
    (disable with "--vsys 1 --unit 5 --ignore")
 6: Network adapter: orig NAT, config 3, extra slot=0;type=NAT
 7: CD-ROM
    (disable with "--vsys 1 --unit 7 --ignore")
 8: IDE controller, type PIIX4
    (disable with "--vsys 1 --unit 8 --ignore")
 9: IDE controller, type PIIX4
    (disable with "--vsys 1 --unit 9 --ignore")
10: SATA controller, type AHCI
    (disable with "--vsys 1 --unit 10 --ignore")
11: Hard disk image: source image=VBox-disk2.vmdk, target path=D:\VBox\Gentoo\VBox-disk2.vmdk, controller=10;channel=0
    (change target path with "--vsys 1 --unit 11 --disk path";
    disable with "--vsys 1 --unit 11 --ignore")
12: Hard disk image: source image=VBox-disk3.vmdk, target path=D:\VBox\Gentoo\VBox-disk3.vmdk, controller=10;channel=1
    (change target path with "--vsys 1 --unit 12 --disk path";
    disable with "--vsys 1 --unit 12 --ignore")
Virtual system 2:
 0: Suggested OS type: "WindowsXP"
    (change with "--vsys 2 --ostype <type>"; use "list ostypes" to list all possible values)
 1: Suggested VM name "MIS_ORACLE"
    (change with "--vsys 2 --vmname <name>")
 2: Number of CPUs: 1
    (change with "--vsys 2 --cpus <n>")
 3: Guest memory: 1024 MB
    (change with "--vsys 2 --memory <MB>")
 4: Sound card (appliance expects "", can change on import)
    (disable with "--vsys 2 --unit 4 --ignore")
 5: USB controller
    (disable with "--vsys 2 --unit 5 --ignore")
 6: Network adapter: orig NAT, config 2, extra slot=0;type=NAT
 7: Network adapter: orig Internal, config 2, extra slot=1;type=Internal
 8: CD-ROM
    (disable with "--vsys 2 --unit 8 --ignore")
 9: IDE controller, type PIIX4
    (disable with "--vsys 2 --unit 9 --ignore")
10: IDE controller, type PIIX4
    (disable with "--vsys 2 --unit 10 --ignore")
11: Hard disk image: source image=VBox-disk4.vmdk, target path=D:\VBox\MIS_ORACLE\VBox-disk4.vmdk, controller=9;channel=0
    (change target path with "--vsys 2 --unit 11 --disk path";
    disable with "--vsys 2 --unit 11 --ignore")
Virtual system 3:
 0: Suggested OS type: "WindowsXP"
    (change with "--vsys 3 --ostype <type>"; use "list ostypes" to list all possible values)
 1: Suggested VM name "MUD_"
    (change with "--vsys 3 --vmname <name>")
 2: Number of CPUs: 1
    (change with "--vsys 3 --cpus <n>")
 3: Guest memory: 1881 MB
    (change with "--vsys 3 --memory <MB>")
 4: Sound card (appliance expects "", can change on import)
    (disable with "--vsys 3 --unit 4 --ignore")
 5: USB controller
    (disable with "--vsys 3 --unit 5 --ignore")
 6: Network adapter: orig NAT, config 2, extra slot=0;type=NAT
 7: CD-ROM
    (disable with "--vsys 3 --unit 7 --ignore")
 8: IDE controller, type PIIX4
    (disable with "--vsys 3 --unit 8 --ignore")
 9: IDE controller, type PIIX4
    (disable with "--vsys 3 --unit 9 --ignore")
10: Hard disk image: source image=VBox-disk5.vmdk, target path=D:\VBox\MUD_\VBox-disk5.vmdk, controller=8;channel=0
    (change target path with "--vsys 3 --unit 10 --disk path";
    disable with "--vsys 3 --unit 10 --ignore")
Virtual system 4:
 0: Suggested OS type: "Windows7"
    (change with "--vsys 4 --ostype <type>"; use "list ostypes" to list all possible values)
 1: Suggested VM name "Win7"
    (change with "--vsys 4 --vmname <name>")
 2: Number of CPUs: 4
    (change with "--vsys 4 --cpus <n>")
 3: Guest memory: 5216 MB
    (change with "--vsys 4 --memory <MB>")
 4: Sound card (appliance expects "", can change on import)
    (disable with "--vsys 4 --unit 4 --ignore")
 5: USB controller
    (disable with "--vsys 4 --unit 5 --ignore")
 6: Network adapter: orig NAT, config 3, extra slot=0;type=NAT
 7: CD-ROM
    (disable with "--vsys 4 --unit 7 --ignore")
 8: IDE controller, type PIIX4
    (disable with "--vsys 4 --unit 8 --ignore")
 9: IDE controller, type PIIX4
    (disable with "--vsys 4 --unit 9 --ignore")
10: SATA controller, type AHCI
    (disable with "--vsys 4 --unit 10 --ignore")
11: Hard disk image: source image=VBox-disk6.vmdk, target path=D:\VBox\Win7\VBox-disk6.vmdk, controller=10;channel=0
    (change target path with "--vsys 4 --unit 11 --disk path";
    disable with "--vsys 4 --unit 11 --ignore")
12: Hard disk image: source image=VBox-disk7.vmdk, target path=D:\VBox\Win7\VBox-disk7.vmdk, controller=10;channel=1
    (change target path with "--vsys 4 --unit 12 --disk path";
    disable with "--vsys 4 --unit 12 --ignore")
Virtual system 5:
 0: Suggested OS type: "WindowsXP"
    (change with "--vsys 5 --ostype <type>"; use "list ostypes" to list all possible values)
 1: Suggested VM name "WinXP_SQL"
    (change with "--vsys 5 --vmname <name>")
 2: Number of CPUs: 1
    (change with "--vsys 5 --cpus <n>")
 3: Guest memory: 2048 MB
    (change with "--vsys 5 --memory <MB>")
 4: Sound card (appliance expects "", can change on import)
    (disable with "--vsys 5 --unit 4 --ignore")
 5: USB controller
    (disable with "--vsys 5 --unit 5 --ignore")
 6: Network adapter: orig Bridged, config 2, extra slot=1;type=Bridged
 7: CD-ROM
    (disable with "--vsys 5 --unit 7 --ignore")
 8: IDE controller, type PIIX4
    (disable with "--vsys 5 --unit 8 --ignore")
 9: IDE controller, type PIIX4
    (disable with "--vsys 5 --unit 9 --ignore")
10: Hard disk image: source image=VBox-disk8.vmdk, target path=D:\VBox\WinXP_SQL\VBox-disk8.vmdk, controller=8;channel=0
    (change target path with "--vsys 5 --unit 10 --disk path";
    disable with "--vsys 5 --unit 10 --ignore")

При распаковке виртуальной машины Windows7 возникает ошибка

Progress state: E_FAIL VBoxManage.exe: error: Appliance import failed
  VBoxManage.exe: error: Internal inconsistency looking up disk image
  'vmdisk6' VBoxManage.exe: error: Details: code E_FAIL (0x80004005),
  component Appliance, i nterface IAppliance VBoxManage.exe: error:
  Context: "int __cdecl handleImportAppliance(struct Handle rArg *)" at
  line 781 of file VBoxManageAppliance.cpp

Эта виртуальная машина не самая необходимая, но из-за неё невозможно распаковать остальные. Пытался решить проблему так:

D:>vboxmanage import vbox.ova --vsys 3 --vmname MUD --vsys 4 --unit 4
  --ignore --unit 5 --ignore --unit 7 --ignore --unit 8 --ignore --unit 9 --ignore --unit 10 --ignore --unit 11 --ignore --unit 12 --ignore

То есть пытался отключить импорт этой машины. Не помогло, та же ошибка. Есть ли способ вообще отключить импорт этой машины и диска vmdisk6?

A:

Файл с расширением ova (File Virtualization Format Archive) это архив в формате tar. Попробуйте переименуйте свой файл VBox.ova в VBox.tar и распакуйте любым архиватором который поддерживает этот формат, тот же 7zip. Дальше можно импортировать неповрежденные машины.


Q:

Predictions based on k-fold Cross Validation, which model is used (Caret)

I am sorry if there is an obvious or intuitive answer to this, which I missed.
We have tuned the hyperparameters of a RF using Grouped 10 - Fold CV (repeated 5 times), to obtain the values for mtry and ntree which result in the highest accuracy.
I understand the concept of (grouped) K-Fold Cross Validation. However my first basic question is how is the hyperparameter tuning from caret incorporated into this resampling technique? In a toy example where we want to test mtry = c(1,2) and ntree = c(500,1000) (meaning 4 possible combinations of hyperparameters) would caret run the complete 10 Fold CV repeated 5 times, for each of the 4 possible combination of mtry and ntree?
Or does caret iterate through the different hyperparameter combinations in the repeats of the CV?
Furthermore if we want to make predictions about a novel dataset (df2) based on the rf model (output from caret hyperparam tuning), which model will be used? Since in a 10-Fold CV there are 10 models trained on (10-1 Fold of data) and evaluated in 1 fold. I know that the performance metrics are averaged, however I can't really imagine that the same is true for the model.
transfer <- predict(rf.df1,newdata = df2)
confusionMatrix(df2$Class,transfer)
#which model is used here for the predictions?

A:

The model used is the one trained on the whole of the training sample using the hyperpameters yielding the optimal average performance based on the CV procedure defined.


Q:

Math without numbers

You must write functions for addition, subtraction, multiplication, and division; however, you can never use any of your language's number types / primitives -- this means no ints, no floats, no Integers; no nothing. You cannot reference these types at all; not even implicitly, e.g. no pushing and popping numbers on a stack.
Valid statically-typed pseudocode (does not solve the problem):
boolean result = true && false
string helloWorld = "hello" + " world"
Object[] things = [new Object(), "foo", true]

Invalid statically-typed pseudocode (does not solve the problem):
float num = 42F
Object foo = "100".toInt()

To make things simpler, pointers are allowed.
This is code-golf, so make it short and sweet.

A:

Haskell: 162 characters
This is algebraic data types 101.
data N=E|Z|P N
a x Z=x
a x (P y)=a(P x)y
s x Z=x
s Z _=E
s (P x)(P y)=s x y
m _ Z=Z
m Z _=Z
m x (P y)=a x$m x y
d _ Z=E
d x (P Z)=x
d Z _=Z
d x y=a(P Z)$d(s x y)y


Q:

Better way to identify duplicates in a group in a Pandas dataframe?

I have a dataframe
   x  c
0  0  1
1  3  2
2  1  1
3  2  1
4  3  1
5  4  1
6  1  0
7  3  1
8  2  1
9  1  2

I would like to produce
   c  x duplicated
0  1  0      False
1  2  3      False
2  1  1      False
3  1  2       True
4  1  3       True
5  1  4      False
6  0  1      False
7  1  3       True
8  1  2       True
9  2  1      False

that is to group by c first, and mark all duplicated rows in the group.
My current approach is
c = np.random.randint(0, 3, 10)
x = np.random.randint(0, 5, 10)
d = pd.DataFrame({'x': x, 'c': c})
d['duplicated'] = d.groupby('c').apply(
    lambda x: x.duplicated(keep=False)
).reset_index(level=0, drop=True)

Is there any better way?

A:

Use duplicated only - by default it verify all columns:
d['duplicated'] = d.duplicated(keep=False)
print (d)
   x  c  duplicated
0  0  1       False
1  3  2       False
2  1  1       False
3  2  1        True
4  3  1        True
5  4  1       False
6  1  0       False
7  3  1        True
8  2  1        True
9  1  2       False

d['duplicated'] = d.duplicated(subset=['c','x'],keep=False)
print (d)
   x  c  duplicated
0  0  1       False
1  3  2       False
2  1  1       False
3  2  1        True
4  3  1        True
5  4  1       False
6  1  0       False
7  3  1        True
8  2  1        True
9  1  2       False


Q:

Firebase - Needing to find document id using 'where'

I need to find the document label (name/id?) of a document I acquire with the .where(...)
What am I doing wrong?
   // updates dev team in the db
function updateDevTeam(devToUpdate, update) { // devToUpdate = id of dev, fieldToUpdate = goal, name, or team_id, update = value
    var devToUpdateDocument = fb.db.collection('dev').where('id', '==', devToUpdate) //how do I set this to the document id(/name/path?)
    fb.db.collection('dev').doc(devToUpdateDocument).update({ team_id: update })
}

A:

It looks like you are trying to update all documents that would result from a query.  Firestore doesn't have an "update where" function like SQL.
It's not possible to update a document if you don't have a reference to that document.  To update all the documents that match a query, you have to:

Actually perform the query
Iterate all the documents in the result

Get a reference to the document
Update it individually

// Your query object
const query = fb.db.collection('dev').where('id', '==', devToUpdate)
// now actually perform the query to get a QuerySnapshot
query.get().then(qsnapshot => {
    // then iterate each document in the result set to update it
    qsnapshot.docs.forEach(dsnapshot => {
        // get a reference to the document in the DocumentSnapshot
        const ref = dsnapshot.ref
        // and update it
        ref.update(...)
    })
})


Q:

How to display video as icons in website?

Is there a way to display the video in a website page as an arranges icons of videos or thumbnails, so whenever I click on one video it should open a new window to play that video? not play it in the same page.
as this code, but the target="_blank" not leading me to another page?

        <object type="video/x-ms-wmv" data="Videos/clock.avi" width="320" height="255" >
            <param name="src" value="Videos/clock.avi">
            <param name="autoStart" value="0">
            alt : clock.avi
        </object>

A:

When you see that with Youtube or other streaming website, is not VideoObject was open a website with video, is just a link to one page with the same video...
You have lot of method for create this "effect" , for optimize, you want just load One image (for create a thumbnails) of your video for create the link

because, it's unnecessary to load your video, if it's just for link here in other page...
In your video Page, you can juste play your video...

    <object type="video/x-ms-wmv" data="Videos/clock.avi" width="320" height="255" >
        <param name="src" value="Videos/clock.avi">
        <param name="autoStart" value="0">
    </object>

If you've few competences in your language ( aspx, html ? ) you want to create one same page for all your videos, with a parameter in your  link in all thumbnails...
For sample, you can create two thumbnails with the same link, and just parameter change :
sample with php link :

and you received parameters in your video page : (always with php...)

    <object type="video/x-ms-wmv" data="Videos/clock.avi" width="320" height="255" >
        <param name="src" value="<?php echo $_GET["myvideo"]; ?>">
        <param name="autoStart" value="0">
    </object>

I use .php for sample because I'm not familiar with .aspx but you can make this sample in .aspx :-)


Q:

Comparing NSString

The output of the code below is,

areEqual
areEqual

Can somebody explain why?
NSString *firstUserName = @"nick";
NSString *secondUserName = @"nick";

if (firstUserName  == secondUserName)
{
    NSLog(@"areEqual");
}
else
{
    NSLog(@"areNotEqual");
}

MyObject *object1 = [[MyObject alloc]init];
object1.identifier = @"1";
MyObject *object2 = [[MyObject alloc]init];
object2.identifier = @"1";

if (object2.identifier  == object1.identifier)
{
    NSLog(@"areEqual");
}
else
{
    NSLog(@"areNotEqual");
}

A:

When you explicitly type @"nick" or @"1", it is a string literal that, for efficiency, the compiler is storing in the same memory location. If you created one of the strings in a different fashion, it would appear at a different memory location, such as if you built up the first string by concatenating two strings together.
Generally comparing two strings in this way is not what you want to do. Usually you want to compare the two strings for equality, and rarely want to know if they actually point to the same memory address. You should use isEqual: or isEqualToString: instead.


Q:

AngularJS - Automatically update md-autocomplete search list based on another md-autocomplete input

I have two <md-autocomplete> drop-downs. I would like to update the search list of the second drop-down based on the selection of the first dropdown.
Here is a prepared non-working plunker : http://plnkr.co/edit/GxQujjAcxYdawlANJd9O?p=preview
Description of wanted behavior:
when a user selects let's say "This is an A" from the first drop-down, I would like to update options to $scope.numbersA, that is [1, 2, 3]. For input "This is a B" the corresponding number array is $scope.numbersB, etc.
I cannot get this to work properly, on my app there is $http request for every change on the first drop-down. As specified here I am using .then() and not .success(). I have simplified the example in plunker because there is less code :)
Edit:
I have just noticed the searchText in plunker is not working properly, that's because of my search function. This is not an issue, it works as it should on my app.

A:

Use md-no-cache to invoke the search handler every time user types value in second autocomplete.
Pass first autocomplete selected value as argument for search handler of second autocomplete
Try this:

// Code goes here
var app = angular.module('app', ['ngMaterial']);

app.controller('ctrl', ['$scope',
  function($scope) {
    $scope.letters = [{
      'display': 'This is an A',
      'value': 'a'
    }, {
      'display': 'This is a B',
      'value': 'b'
    }, {
      'display': 'This is a C',
      'value': 'c'
    }];
    $scope.numbersA = [1, 2, 3];
    $scope.numbersB = [4, 5, 6];
    $scope.numbersC = [7, 8, 9];

    $scope.getMatchesLetter = function(query) {
      if (query === null || query === "" || query === undefined)
        return $scope.letters;

      var results = query ? $scope.letters.filter(createFilterFor(query)) : $scope.letters;
      return results;
    };

    $scope.getMatchesNumber = function(query, selected) {
      var arrToSearch;
      switch (selected.value.toUpperCase()) {

        case 'A':
          arrToSearch = $scope.numbersA;
          break;

        case 'B':
          arrToSearch = $scope.numbersB;
          break;

        case 'C':
          arrToSearch = $scope.numbersC;
          break;

      }
      if (query === null || query === "" || query === undefined)
        return arrToSearch;

      var results = query ? arrToSearch.filter(createFilterFor(query)) : arrToSearch;
      return results;
    };

    $scope.itemChange = function(item, whichOne) {
      switch (whichOne) {
        case 'A':
          $scope.numbersA = item;
          break;
        case 'B':
          $scope.numbersB = item;
          break;
        case 'C':
          $scope.numberC = item;
          break;
      }
    };

    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(state) {
        //return (state.value.indexOf(lowercaseQuery) === 0); // startsWith()
        return (state.value.search(lowercaseQuery) != -1); // contains()
      };
    }

  }
]);;
<!DOCTYPE html>

  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.css">

  <md-autocomplete md-selected-item="selectedItemLetter" md-search-text="searchTextLetter" md-selected-item-change="itemChange(item)" md-items="item in getMatchesLetter(searchTextLetter)" md-item-text="item.display" md-min-length="0" placeholder="Select letter">
    <md-item-template>
      {{item.display}}
    </md-item-template>
    <md-not-found>No matches found.</md-not-found>
  </md-autocomplete>

  <md-autocomplete md-selected-item="selectedItemNumber" md-search-text="searchTextNum" md-selected-item-change="itemChange(item)" md-items="item in getMatchesNumber(searchTextNumber,selectedItemLetter)" md-no-cache="true" md-item-text="item" md-min-length="0"
  placeholder="Select number">
    <md-item-template>
      {{item}}
    </md-item-template>
    <md-not-found>No matches found.</md-not-found>
  </md-autocomplete>


Q:

How can I safely port my wordpress blog to localhost?

I'm trying to make local development copies for my wordpress blog. I tried first to install wordpress locally (on XAMPP for Windows), install the plugins then import the live data (from a DB backup). The problem is whenever I import the live data I start getting all sorts of errors, even after I change the blog's URL through the database.
Also, the redirection rules I have on my server don't seem to work locally (whether set by wordpress or some of its plugins).
So is there a safe way to just grab the whole thing and make it work locally exactly like the server?
Your help is much appreciated :)

A:

get a full backup of all the files in your online wordpress installation
get a complete backup of the database in use
with any text editing software, process the SQL file of the database backup and change every occurrence of http://old.site with http://localhost
extract the files to your document root
edit wp-config.php to tweak database host/user/pass
import the modified SQL backup
login into admin panel, go to Options->Permalink and save to update permalinks

No need to install anything, just grab what you have online. On windows you might have to rename .htaccess


Q:

how to display only aggregate or flagged results in a Case statement

I have a query that gets break time exceptions.  I use Case statements to flag the records.  The problem is, I only want to list those that are flagged or have a "1" in the Skipped break, or "ShortBreak" column?
SELECT        lEmployeeID, sFirstName, sLastName, SUM(TotalHours) AS TotalHours, DATEDIFF(mi, MIN(dtTimeOut), MAX(dtTimeIn)) AS BreakTime,
                         CASE WHEN SUM(ftc.TotalHours) > 6 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 0 THEN 1 ELSE 0 END AS SkippedBreak, CASE WHEN DATEDIFF(mi,
                         MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 30 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) > 0 THEN 1 ELSE 0 END AS ShortBreak
FROM            dbo.fTimeCard(@StartDate, @EndDate, @DeptList, @iActive, @EmployeeList) AS ftc
WHERE        (DID IS NOT NULL) OR
                         (DID IS NOT NULL) AND (dtTimeOut IS NULL)
GROUP BY lEmployeeID, sFirstName, sLastName, TotalHours

A:

You cannot filter in the WHERE part of the query you've got, because the grouping is not yet performed at that point. You can use a HAVING clause to do additional filtering after grouping:
SELECT        lEmployeeID, sFirstName, sLastName, SUM(TotalHours) AS TotalHours, DATEDIFF(mi, MIN(dtTimeOut), MAX(dtTimeIn)) AS BreakTime,
                     CASE WHEN SUM(ftc.TotalHours) > 6 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 0 THEN 1 ELSE 0 END AS SkippedBreak, CASE WHEN DATEDIFF(mi,
                     MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 30 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) > 0 THEN 1 ELSE 0 END AS ShortBreak
FROM            dbo.fTimeCard(@StartDate, @EndDate, @DeptList, @iActive, @EmployeeList) AS ftc
WHERE        (DID IS NOT NULL) OR
                     (DID IS NOT NULL) AND (dtTimeOut IS NULL)
GROUP BY lEmployeeID, sFirstName, sLastName, TotalHours
HAVING SUM(ftc.TotalHours) > 6 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 0
OR DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 30 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) > 0

Or you can use a subquery, and filter the results of the subquery:
SELECT *
FROM (
SELECT        lEmployeeID, sFirstName, sLastName, SUM(TotalHours) AS TotalHours, DATEDIFF(mi, MIN(dtTimeOut), MAX(dtTimeIn)) AS BreakTime,
                     CASE WHEN SUM(ftc.TotalHours) > 6 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 0 THEN 1 ELSE 0 END AS SkippedBreak, CASE WHEN DATEDIFF(mi,
                     MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 30 AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) > 0 THEN 1 ELSE 0 END AS ShortBreak
FROM            dbo.fTimeCard(@StartDate, @EndDate, @DeptList, @iActive, @EmployeeList) AS ftc
WHERE        (DID IS NOT NULL) OR
                     (DID IS NOT NULL) AND (dtTimeOut IS NULL)
GROUP BY lEmployeeID, sFirstName, sLastName, TotalHours
) AS sub
WHERE sub.SkippedBreak = 1 OR sub.ShortBreak = 1


Q:

in jQuery, how to remove an element that has only one whitespace?

Given the following HTML on a page:

test text 1

test text 2

test text 3

text4

How can I completely remove the 4th line   using jQuery?
If it helps any, I'm able to find it via regex:
var re = new RegExp("]*test2[^>]*> ]*?>");

And I'm able to find and remove any node with that class using jQuery:
$("span[class*='test2']").remove();

But this removes ALL nodes that have the class "test2" which is not what I want; I only want to remove the one with the single whitespace in it.  $("span[class*='test2']:empty").remove(); does not work as that node is not empty, and has a whitespace.
I feel I'm very close, but I'm missing something; I would like the result to be:

test text 1

test text 2

test text 3

text4

Any clues?

A:

       $('span').each(function(){
               var str = $(this).text().replace(/ /g,'');
               if (str.length < 1){
                   $(this).remove();
               }
          });

A:

This should do it:
$("span[class*='test2']").filter
                (
                  function() {
                      return $(this).text() === " ";
                  }
                ).remove();


Q:

Snowflake - Select unique rows based on primary key from staging area

In the case I have staged area created from a csv file that has two rows with the same primary key value 5 and another row with value 6. Is there a way that I can run a select query (used for a copy into later) that can get the last row with primary key 5 and the row with 6? Collectively only returning the two unique primary key rows (preferably the last one).
After I've "put" my file into the staging area, I understand to get my columns and values I'd run the following:
select t.$1, t.$2, t.$3, t.$4 from @MY_STAGE( FILE_FORMAT => 'csv') t and the would get all 3 rows and their respective columns and values in order. Is there a way that I can improve the query to return two rows, one of with primary key 5 and one for key 6?
Thanks in advance.

A:

This might help:
select Distinct * from @MY_STAGE( FILE_FORMAT => 'csv') t

Or a row_number() over ( Partition By Primary_key Order By < a suitable column > ) = 1.
Are the 2 rows with same primary key exactly the same or do some values differ (like if primary key is 5, do some other columns have different values)?


Q:

I was wondering if the set of singular loops is a (somewhere) submanifold of loop space?

The set of all smooth maps $S^1\to M^n$ ($M$ is a smooth manifold) is a generalized manifold(see http://ncatlab.org/nlab/show/smooth+loop+space).
I was wondering if the set of singular loops (maps with selfcrossings or zeros of derivative) is a (Fréchet,Frolicher,diffeological)submanifold of loop space?
EDIT: it is clear that answer is no (see answer below). So, I rewrite question: is it true that set of singular loops is a collection of submanifolds different codimension(set of loops with one selfintersection has codimension $dim M-2$, loops with zero of derivative has codimension $dim M -3$ and so on. Set of loops with infinite number of singularities should have infinite codimension... Let's forget about them.)
So, the question is about local situation: for example, let's consider a loop with one self-intersection (and without other singlarities). Is it true that set of near loops with one self-intersection is a submanifold in sense of (Fréchet|Frolicher|diffeological)?
EDIT 2. I reformulate question. $map(S^1 \to \mathbb R^3)$ is a functional space, so we can apply a technique of singularity theory. Generic map $f$ with one self-intersection has one-parameter versal deformation $V:[0,1]\times S^1\to \mathbb R^3$ - and any deformation are induced from $V$. Does it imply that $D$(set of singular loops) near the $f$ is a submanifold of codimension 1 in sense of Fréchet or Frolicher?
ADDED. Andrew Stacey explains in his answer and in http://ncatlab.org/nlab/show/on+the+manifold+structure+of+singular+loops why a stratum of a loop space is not a submanifold (the reason is tha same as in a standart smooth injection of line to plane where image is not a submanifold).
But locally, as Ryan said, each stratum is a submanifold (in sense of Frechet). And the kast question is:
For a smooth submanifold $X⊂Y$ of codimension 2, for a general point $x∈X$ we always have a map from small neghbourhood $U$ of $x$ to $D^2$ ($x∈U⊂Y,f:U→D^2$) such that $U\cap X= f^{−1}(0)$. I belive that in situation of space of loops there is no such map... Is it true?

A:

Let $L(M)$ be the space of smooth maps from $S^1$ to $M$.
Let $D(M)$ be the subspace of $L(M)$ consisting of immersions $f : S^1 \to M$ where $f$ admits a unique pair of points $p,q \in S^1$, $p \neq q$ with $f(p)=f(q)$.
My understanding of your question, is you want to know if $D(M) \subset L(M)$ is a submanifold.
I think it's not.
"Most" (*) of $D(M)$ has co-dimension $m-2$ in $L(M)$, where $dim(M)=m$.  But the problem is $D(M)$ is a stratified space.  $D(M)$ has a subspace where $f'(p)$ and $f'(q)$ are linearly dependent.  Call this $D'(M)$.  The reason for the asterix is that $D(M) \setminus D'(M)$ has co-dimension $m-2$ in $L(M)$. This is a genuine submanifold, and you get "charts" by doing the Vassiliev resolution-of-singularities, as $D(M) \setminus D'(M)$ is just immersions that have a single regular double point.
So the problem is getting charts around points of $D'(M)$.  They don't exist.  You can make the argument in general, but let's just take $M = \mathbb R^3$ just to make it somewhat concrete.   Take a local picture that looks like the graph of the functions:
$$ t \longmapsto (t,0,0)$$
i.e. the x-axis
and
$$ t \longmapsto (t,t^2,0) $$
So this these are meant to be conjugate to two intervals of a map $f : S^1 \to \mathbb R^3$, describing a quadratic-type double point.
We consider a little neighbourhood of $f$ by doing a small perturbation to $f$ in $L(M)$.
$$ t \longmapsto (t,t^2+a, bx+c)$$
This is the original map when $a=b=c=0$.  Its in $D'(M)$ only for that original map.  For $a>0$ there are no singularities at all, but for $a<0$ there are the singularities corresponding to all parameters that satisfy
$$\pm b\sqrt{-a}+c=0$$
but the central singularity, where $b=c=0$ is one with two regular double points.
So this means that if $f \in D'(M)$, there are no manifold charts for $D(M)$ in $L(M)$ centered around $f$, since there are four "sheets" of $D(M) \setminus D'(M)$ incident to these points.  $D(M)$ isn't locally flat about these points.
edit: Here is how you argue that $D(M) \setminus D'(M)$ is a submanifold of $L(M)$.  Given a point $f \in D(M) \setminus D'(M)$ it is an immersion $S^1 \to M$ which is an embedding except for a single regular double point, meaning $f(p)=f(q)$ for $p,q \in S^1$, $p \neq q$, and $f'(p)$ and $f'(q)$ are linearly independent.  The tangent space to $f$ is the sections of the pull-back $f^o(TM)$ bundle.  The tangent space to $D(M) \setminus D'(M)$ at $f$ is given by certain constrained tangent vector fields along $f$.  Thinking of $f^o(TM)$ as the tangent space to $L(M)$, it's the subspace of $f^o(TM)$ such that if $p,q \in S^1$ are the double points, then the vector over $p$ and the vector over $q$ are both tangent vectors in $T_{f(p)}M$, and we demand that the components of these vectors normal to $img(Df_p) \oplus img(Df_q)$ agree.  By design, this is a $(m-2)$-dimensional constraint.  The Vassiliev resolution of singularities idea -- pushing off the double-point -- is the complementary space to the tangent space of $D(M)\setminus D'(M)$ in $L(M)$.  So this is a splitting of $T_f(L(M))$ into $T_f(D(M)\setminus D'(M)$ direct sum with an $(m-1)$-dimensional space corresponding to the deformations that remove the singularity. This also gives you your submanifold charts for $D(M)\setminus D'(M)$ at $f$.
Note: I meant to use standard notation for pull-backs but raising an asterix in math mode does strange things.  So I use $f^o(bundle)$ instead.
Technically, what I've described in "edit" is a splitting of the tangent space to $L(M)$ at a point $f \in D(M) \setminus D'(M)$.  The sub-manifold chart for $D(M) \setminus D'(M)$ is precisely the same chart as you use for $L(M)$ at $f$, but pre-composed with this splitting isomorphism.  That this map is a submanifold chart for $D(M)\setminus D'(M)$ amounts to the observation that you can break this flow up into an isotopy that carries $img(Df_p) \oplus img(Df_q)$, together with a motion of the two arcs in this 2-dimensional space (which isn't an isotopy, it's just a 1-parameter family of immersions).

A:

I started answering this question, as much to understand how to fit Torsten and Ryan's arguments into what I already know, but the answer got a bit long.  Since I find the input format here a little constricting, I ended up writing it as an nLab page and have posted it there.  Here's the summary:

Torsten and Ryan are correct: none of the variants of the spaces that you have described (to date) can be thought of as a submanifold of the smooth loop space.  In my answer I try to expand on these objections a little, but the core of the objections are those that they describe.
In particular, Ryan's objection is based on the fact that the space of loops with a exactly one coincidence point is not an open subset of the space of loops with at least one coincidence point.  (Contrast this with the fact that the space of loops with no coincidence points is a submanifold of the space of all loops.)
There is a smooth manifold nearby.  It is the space of singular loops with a marked coincidence point.  (One could also take, as Ryan says, the subspace of singular loops with a single coincidence point and linearly indepdendent tangent vectors at that point.)
In considering how to go from a marked loop to an unmarked one, we can see (hopefully clearly) why we do not get a manifold.

The nlab page is at: http://ncatlab.org/nlab/show/on+the+manifold+structure+of+singular+loops (though I think that the title would be better as "on the manifold structure of singular loops, or lack thereof").

A:

The following argument I think should work to prove that the answer is no (though I haven't checked whether it really fits in with the proper definition): Consider a loop where three points of $S^1$ maps to the same point in $M$ but with linearly independent (to be on the safe side) tangents. Then you keep within the singular loops by moving two of the three points in the same way but the third in any which way. To first order that should correspond to a $TM$-valued vector field on $S^1$ which is the same at the two points but arbitrary at the third. However, there are three possibilities for the choice of the two points that should travel together and all the vector fields that you get from varying the choices will not form a linear subspace. Hence what you get is rather three submanifolds (corresponding to the three choices) coming together meeting transversally.


Q:

An executable and a shared library dependent on a same statically linked library

Suppose you're developing a shared library libshared.so.
And you have a static library libstatic.a with some internal classes and functionality you need. You'd like to link it to your .so like this:
g++ -o libshared.so -shared myObj.o -lstatic

Also you have an executable.sh which will use your .so and dynamically open it in the runtime
dlopen("libshared.so", RTLD_NOW)
You know this executable was as well statically linked against libstatic.a (but you're not sure the version of the library is exactly the same as yours).
So the question is:
Is it safe and correct to statically link your libshared.so against libstatic.a when you know the same library is already used in executable.sh?

A:

You should avoid linking a static library into a shared one.
Because a shared library should have position independent code (otherwise, the dynamic linker has to do too much relocation, and you lose the benefits of shared libraries), but a static library usually does not have PIC.
Read Drepper's paper: How to write a shared library
You build your library with
  g++ -Wall -O -fPIC mySrc.cc -c -o myObj.pic.o
  g++ -o libshared.so -shared myObj.pic.o -lotherlib


Q:

How to disable/ hide delete button for column in list in SharePoint Online?

I have a calculated field in my custom list. I want to disable or hide delete button on this field edit page. I want specific users not able delete this column in a list but still be able to edit/ delete other columns in the same list. Please see below screenshot for field:

I have tried below things:

Checked adding column as site column and added in content type. Then associate content type in list. But it is not restricting delete.
Checked SharePoint Online Powershell. But not able to set sealed property for this column.
I can't apply permission break as I want users to be able to manage other columns in list

Is there any other way that we can do this? Is PNP-Powershell has any cmdlets that can help me achieve this?

A:

One option (strongly unsupported by Microsoft) is to add custom Javascript (JS) in masterpage file, targeting this specific button for this specific field:
1) create JS file and store in SP --> code alters target button by hiding it or deleting (or how is more convenient for You)
2) create custom masterpage based on original (never-ever-ever edit the original masterpage)
3) insert link to previously created JS file
4) enjoy.


Q:

Is it possible to get all the slabs (tiles) in the Holy Sanctum, and does it give any bonus or achievement?

I always end up with one or two missing slabs (or tiles or platforms, if you prefer) in the Holy Sanctum in the 4th act.  Is it possible to get all the slabs, and is there any reason to do so?  Bonus loot?  A feat of strength achievement?

A:

It is possible, but no, nothing interesting happens.
I completed all the slabs on my last run through this dungeon (Hell difficulty), and absolutely nothing happened other than the mobs that spawn when you step on a new slab.
Partway through, I managed to get to the far corner, where there was a Resplendent Chest waiting for me, but it definitely was there well before all of the tiles were filled in.


Q:

Why is  tag called link?

I Was wondering why is <link /> tag in HTML is called link. Why not call it something like <include /> as it includes things such as stylesheets? What does the word link actually signify? Why was link used?

A:

Per the HTML Living Standard:

The link element allows authors to link their document to other resources.

It's used to link to other resources. It's used to describe and specify a relationship between the document and another resource which may be a stylesheet, it's not necessarily importing a resource. The name include would entail that you're including a script or stylesheet, but that's not what link necessarily does.


Q:

Хвороб чи хворіб?

Побачила на різних сайтах такі формулювання: "Картини хворіб і лікування" (Клініка Піраварт), "5 хворіб, в боротьбі з якими корисно пити каву" (Українські новини) та "Перелік інфекційних хвороб людини" (Вікіпедія), "Симптоми хвороб - зовнішні ознаки захворювань від А до Я" (Eurolab).
Теоретично мало б бути чергування хвороба - хворіб за аналогією дорога - доріг і ця форма мала б бути правильною.
Отже, то яка із форм є правильною: хвороб чи хворіб? Що зумовило широке використання помилки?

A:

У Словниках онлайн (Орфографічний словник) знаходимо:

ВІДМІНОК  ОДНИНА  МНОЖИНА
  Називний - хвороба,   хвороби.
  Родовий - хвороби,    хвороб.
  Давальний - хворобі,  хворобам.
  Знахідний - хворобу,  хвороби.
  Орудний - хворобою, хворобами.
  Місцевий - хворобі,   на/у хворобах.
  Кличний - хворобо,    хвороби.

Отже, правильно: Р. В. мнж. слова "хвороба" - хвороб.
Також знаходимо у Культура \ Мова \ Проблеми мови таке:

2.??? хвороб чи хворіб
В сполученнях -оро-, -оло-, -ере-, -еле- (т.зв. "повноголосся": голос,
  мороз, шелест, очерет) о, е переходять в і:
1) у родовому відмінку множини іменників жіночого роду (здебільшого з
  рухомим наголосом) і в похідних від них іменниках на -к(а) зі
  значенням зменшеності: борода- борід- борідка, голова- голів- голівка
  (і головка- з іншим значенням), сторона- сторін- сторінка. 2) у
  родовому відмінку множини іменників здебільшого середнього роду й
  відповідних зменшених іменниках: болото- боліт- болітце, ворота-
  воріт- ворітця, долото- доліт- долітце, але: дерево- дерев- деревце,
  джерело- джерел- джерельце;
Винятки: a. поріг, моріг, оборіг, сморід;
Чергування о, е з і не відбувається:
О, е в закритому складі не переходять в І 1) у повноголосних формах
  -оро-, -оло- ере-, -еле зі сталим наголосом іменників переважно жіночого роду, від яких немає зменшених форм з і: колоди -колод
  (колодка), долоні - долонь (долонька); сороки - сорок, огорожі -
  огорож, нагорода - нагород

Іменник "хвороба" -ж.р.,сталий наголос,"О, е в закритому складі не переходять в І 1) у повноголосних формах -оро-, -оло- ере-, -еле зі сталим наголосом іменників переважно жіночого роду, від яких немає зменшених форм ".
А помилково вживають, тому що, відміняють за аналогією до "боліт, воріт" і інших, не враховуючи інших мовних нюансів.


Q:

Linux - Get to Shell before other driver boot up

How can I edit my startup scripts in linux so that I get to the login screen as soon as possible? I want all the other accessories (such as Bluetooth, Wifi, Ethernet) drivers to run ONCE I have gotten to the login screen and can now log into shell.
The only thing I can think of is to change the rmnologin order so that it runs before anything else. Is that a good idea?

A:

Use a dependency based init tool like systemd or startpar, then if you still don't have prompt fast enugh dependency reasearch (or trial and error) would be in order. Also set your bios to fast boot. You can also boot into single user mode then change run level later if you want.


Q:

sigma algebra generated by fraction of random variables (continued)

Suppose $X_1,X_2,X_3$ are positive i.i.d. random variables.
Let $S=X_1+X_2+X_3$. Is this true that
$$
\sigma(X_1,X_2)\subset\sigma(X_1/S,X_2/S)?
$$
Any hint of this will be appreciated. Thanks.

A:

Let $\Omega=\{1,2\}^3$ with the uniform probability law, and let $X_i$ be the projection onto the $i$th coordinate. Then $\mathcal{F}_1=\sigma(X_1,X_2)$ contains the event
$$\{X_1=1\}=\{(1,1,1),(1,1,2),(1,2,1),(1,2,2)\}$$
Suppose for contradiction that $\mathcal{F}_2=\sigma(\frac{X_1}{S},\frac{X_2}{S})$ also contains this event. Since $\mathcal{F}_2$ contains the events
$$\Big\{\frac{X_1}{S}=\frac{1}{4}\Big\}=\{(1,1,2),(1,2,1)\}$$
and
$$\Big\{\frac{X_2}{S}=\frac{2}{5}\Big\}=\{(1,2,2),(2,2,1)\}$$
it follows that $\mathcal{F}_2$ contains
$$ \{(1,1,1)\}=\{X_1=1\}\setminus\Big(\Big\{\frac{X_1}{S}=\frac{1}{4}\Big\}\cup\Big\{\frac{X_2}{S}=\frac{2}{5}\Big\}\Big)$$
But this is a contradiction because $\{(1,1,1),(2,2,2)\}$ is an atom in $\mathcal{F}_2$: it's impossible to distinguish between $(1,1,1)$ and $(2,2,2)$ using $\frac{X_1}{S}$ and $\frac{X_2}{S}$. Therefore $\mathcal{F}_1\not\subset\mathcal{F}_2$.


Q:

tidyeval functions and problems with `View()`

Code chunk #1 and #2 are identical, except for line number 14. Code chunk #1 uses a print() call and code chunk #2 uses the View() call. Code chunk #1 works fine. Code chunk #2 gives the error "Error in FUN(X[[i]], ...) : object 'cal.date' not found". Why?
1
library(tidyverse)
set.seed(1)
graph.data <- tibble(cal.date = as.Date(40100:40129, origin = "1899-12-30"),
                     random_num = rnorm(30, 8, 5))

child_function <- function(df, variable, hor.line = 6) {
  variable <- enquo(variable)
  df <- df %>% mutate(mutation = 2 * !!variable, horizontal.line = hor.line)
}

parent_function <- function(df, date, variable, hor.line = 6) {
  date <- enquo(date)
  variable <- enquo(variable)
  df <- df %>% child_function(!!variable, hor.line) %>% print()  # LINE 14
  p <- ggplot(df, aes(!!date, mutation)) +
    geom_point() +
    geom_hline(aes(yintercept = hor.line))
  p
}

parent_function(graph.data, date = cal.date, variable = random_num, hor.line = 8)

2
library(tidyverse)
set.seed(1)
graph.data <- tibble(cal.date = as.Date(40100:40129, origin = "1899-12-30"),
                     random_num = rnorm(30, 8, 5))

child_function <- function(df, variable, hor.line = 6) {
  variable <- enquo(variable)
  df <- df %>% mutate(mutation = 2 * !!variable, horizontal.line = hor.line)
}

parent_function <- function(df, date, variable, hor.line = 6) {
  date <- enquo(date)
  variable <- enquo(variable)
  df <- df %>% child_function(!!variable, hor.line) %>% View() # LINE 14
  p <- ggplot(df, aes(!!date, mutation)) +
    geom_point() +
    geom_hline(aes(yintercept = hor.line))
  p
}

parent_function(graph.data, date = cal.date, variable = random_num, hor.line = 8)

A:

View() is a side effect function and does not return anything.
Use %T>% from the magrittr package instead of %>% for your second case.
View() ends the pipe such that you will want to have a T pipe instead. I think you can see it more clearly like this
 df %>% child_function(!!variable, hor.line) %>% View() -> df

vs.
 df %>% child_function(!!variable, hor.line) %T>% View() -> df


Q:

Mysqli prepare giving error, even though SQL statement is valid?

I'm having some trouble with a SQL transaction using PHP and mySQL. Here is my statement:
START TRANSACTION;
INSERT INTO listings (title, price, seller, description, time, featured)
              VALUES (?, ?, ?, ?, ?, 0);
SELECT @listingid:=LAST_INSERT_ID();
INSERT INTO pictures (listid, primarypic)
                VALUES (@listingid, 1);
COMMIT;

While this statement works fine when I put it in directly using phpMyAdmin (substituting the ? marks), it seems to fail when I call
$stmt = $mysqli->prepare("statement");

Replace "statement" with the above statement. The fact that it fails before getting to the bind_param of the $stmt leaves me to believe that it is not a problem with the parameters, but rather the query.
Here is the exact error, if it helps:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO listings (title, price, seller, description, time, featured) ' at line 2

Thanks in advance for your help!

A:

I don't think mysqli can handle compound statements like that (especially since there is a separate commit() function).  Instead of START TRANSACTION; at the beginning and COMMIT; at the end, you'd do $mysqli->autocommit(false); before the query and $mysqli->commit(); when you're done.


Q:

How can I carry more ammo in BioShock?

Is there a tonic or something else that increases the amount of ammunition you can carry? Upgrading weapon clip size doesn't increase total ammo capacity.

A:

There is no way to increase your total ammo capacity in BioShock, but it is possible in BioShock 2.
From this thread,

The Alpha Series' second Research Bonus is an increased ammo capacity - I think the amount is 20% of the base capacity.


Q:

see all extenders and custom bindings for observable

Is it possible to see all extenders and bindings attached to an observable within Knockout JS?
Sample View Model:
var viewModel = function(){
  var self = this;

  self.firstName = ko.observable().extend({required: "Please enter a name",
                                           logChange: "first name" });

  self.lastName = ko.observable().extend({ required:true});

}

I am also using several custom bindingHandlers including the Knockout X-Editable Plugin in addition to the KO Validation Plugin
Sample Multi-Page View:

  <input data-bind="value:firstName"/>

   ....

A. Is there a way to query self.firstName() and get a list of all of the extenders?
{required: "Please enter a name", logChange: "first name" }
B. Is there another query that I can run to get all of the bindings handlers that depend upon this observable? Can this be returned as DOM elements?
Basically I am trying to display validation errors for imported data, but I want to append them below  if I am on the 2nd view.
This is simple enough when validating each input individually, but it's getting complicated when using ko.validation.group(viewModel). Even if I iterate over every error, I'm not seeing how I can relate them with the original observable that threw the error.

A:

There is a custom binding you can use

If that is not enough then you have to get creative :D
There is no generic way of seeing all extenders on a observable. KO validation adds a few functions and observables to the extended observable that you can use

clearError
error
isValid
isValidating
rules
setError

You need to create a custom binding to be able to see all bindings attached to a element. This is not a bad thing, its bad practice to have dependencies to the View from the ViewModel. From your custom binding init or update function you have a allBindingsAccessor
ko.bindingHandlers.myBinding = {
    init: function(element, accessor, allBindingsAccessor) {
       var valueAttachedToCheckedBinding = ko.utils.unwrapObservable(allBindingsAccessor().checked);
    }
}


Q:

iOS: Custom back button doesn't work

I use FlatUIKit in my project. I have a custom Back button defined like this:
    [UIBarButtonItem configureFlatButtonsWithColor:[UIColor peterRiverColor]
                              highlightedColor:[UIColor belizeHoleColor]
                                  cornerRadius:3
                               whenContainedIn:[UINavigationBar class], nil];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                                style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                            action:@selector(clickBack)];

And here is my clickBack
 -(void)clickBack{
[self.navigationController popToViewController:[self.navigationController.viewControllers     objectAtIndex:self.navigationController.viewControllers.count-1] animated:YES];

}

The button appears as I want it to but that's it. If I click on it, nothing happens.
Any idea what I did wrong? I'm pretty new to this and never replaced a back button.

A:

You just mentioned in one of your comments that you presented the view controller modally, that's different. You'll want to release the modal view controller. Try this:
[self dismissModalViewControllerAnimated:YES];

The pop method is only going to work if the view you are releasing was pushed onto the navigation controller.
Here's a link to a modal view controller example.
http://timneill.net/2010/09/modal-view-controller-example-part-1/


Q:

How do I databind a control in an item template to the item itself, and not one of its properties?

I've got a WPF ListBox that's databound to an ObservableCollection of type Employee.  In the ItemTemplate, I'm binding the content of controls to various properties, as normal.  But for one of the controls in the template, I've made a custom converter class that it uses, and I'd like the converter to get passed in the Employee object itself as the value, as opposed to one of its' properties.  Is this easy to do?  I don't want to resort to something like adding a read only property to Employee whose getter just says return this.
Thanks in advance!

A:

Just use
{Binding}

or
{Binding Converter={...}}

i.e. without a Path.


Q:

ggplot2 density histogram with custom bin edges

I'm able to plot a density histogram, and I'm able to plot a regular histogram with custom bins, but not both together. Here's my attempt:
library(ggplot2)

vals = c(2.6, 5.2, 4.1, 6.9, 5.7, 5.2, 4.4, 5.5, 6.3, 6.1, 4.7, 1.4)
myplot = qplot(vals, geom = 'blank') +
         geom_line(aes(y = ..density..), stat = 'density',
                   colour = 26, size = 2, alpha = .6) +
         geom_histogram(aes(y = ..density..), binwidth = 1,
                        fill = 28, alpha = 0.3) +
         stat_bin(breaks=seq(-.5,8.5,1)) + xlim(-1, 9)

print(myplot)

If you remove the stat_bin term, the histogram plots correctly as a density histogram, but with default bin locations. Add the stat_bin term, and the bins are correct but it's no longer a density histogram. Any ideas how to get both working?

A:

You can add argument breaks= to the geom_histogram() to set your own break points (you don't have to use geom_histogram() and stat_bin() together because geom_histogram() uses stat_bin() to produce result).
qplot(vals, geom = 'blank') +
  geom_line(aes(y = ..density..), colour=26, stat = 'density', size = 2, alpha = .6) +
  geom_histogram(aes(y = ..density..), fill = 28, alpha = 0.3, breaks=seq(-.5,8.5,1))


Q:

How to work with shimming, third-party scripts, and interdependencies

I'm new to working with RequireJS, and am trying to figure out shimming 3rd-party, interdependent scripts. Specifically, I'm trying to get the Stanford Crypto scripts imported.
Basically, the suite is comprised of the core (jsbn.js, jsbn2.js, base64.js, rng.js, and prng4.js), a basic RSA script (rsa.js), and an extended RSA script (rsa2.js).
rsa.js defines the global variable-object RSAKey, and rsa2.js references it.
function RSAKey() {
  this.n = null;
  this.e = 0;
  this.d = null;
  this.p = null;
  this.q = null;
  this.dmp1 = null;
  this.dmq1 = null;
  this.coeff = null;
}

I've set up my shim in a way that I thought was correct, but I get the error "RSAKey is not defined" in rsa2.js. The following is my shim:
require.config({
    paths: {
        'jsbn': "../StanfordRSA/jsbn.js",
        'jsbn2': "../StanfordRSA/jsbn2.js",
        'base64': "../StanfordRSA/base64.js",
        'rng': "../StanfordRSA/rng.js",
        'prng4': "../StanfordRSA/prng4.js",
        'rsa': "../StanfordRSA/rsa.js",
        'rsa2': "../StanfordRSA/rsa2.js"
    },
    shim: {
        'rsa': {
            deps: ['jsbn', 'jsbn2', 'base64', 'rng', 'prng4'],
            exports: "RSAKey"
        },
        'rsa2': {
            deps: ['rsa']
        }
    }
});

My understanding, then, is that if I set 'rsa2' as a requirement in one of my RequireJS modules, it would look at the shim and see that rsa2 is dependent on rsa, which is dependent on the core and exports RSAKey...But that's not what's happening, and it seems like either rsa isn't loading, or it isn't loading correctly. (Please note that all of this works using raw script tags. I'm trying to convert an already existing, already functioning webapp to RequireJS)
Thoughts?

A:

Your basic setup is correct, except for 2 things:

(really important!) You have to omit the .js extensions!!!
You probably have missed the exact dependencies between the scripts.

After some experimentation and reading the comments at the top of the scripts, the working configuration is:
  require.config({
    paths: {
        'jsbn': "../StanfordRSA/jsbn",
        'jsbn2': "../StanfordRSA/jsbn2",
        'base64': "../StanfordRSA/base64",
        'rng': "../StanfordRSA/rng",
        'prng4': "../StanfordRSA/prng4",
        'rsa': "../StanfordRSA/rsa",
        'rsa2': "../StanfordRSA/rsa2"
    },
    shim: {
        'rng': {
          deps: ['prng4']
        },
        'jsbn2': {
          deps: ['jsbn']
        },
        'rsa': {
            deps: ['jsbn', 'rng'],
            exports: 'RSAKey'
        },
        'rsa2': {
            deps: ['rsa', 'jsbn2'],
            exports: 'RSAKey'
        }
    }
  });

Check out a plunk here.


Q:

MySQL DB migration: change of string length

I'm using SQLAlchemy + alembic to manage my database. I had a string field which was 10 characters long and later on found out that it has to be 20. So I updated the model definition.
class Foo(db.Model):
    __tablename__ = 'foos'
    id = db.Column(db.Integer, primary_key=True)
    foo_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    name = db.Column(db.String(80))

When I run alembic revision --autogenerate, this was not detected. Now I did read the documentation and suspected that this might not be supported. How do I managed such changes in DB gracefully?

A:

You need to enable optional column type checking.
See this for notes on what is checked by default
context.configure(
    # ...
    compare_type = True
)


Q:

How to obtain FireFox newly created window handler?

I have starter new System.Diagnostics.Process and it launchs FireFox. How can I obtain the Handler of that window? Any ideas - C#, winAPI functions... anything (just not ASM ;) )

A:

Once you started the process, you can call process.Refresh() and the  process.MainWindowHandle property will eventually contain the native windows handle of the application's main window.
You might have to wait a little bit after you started the process for it to get populated.
Here is some code:
Process process = new Process();
// Fill process.StartInfo
process.Start();

do
{
    System.Threading.Sleep(100);
    process.Refresh();
}
while(process.MainWindowHandle == IntPtr.Zero && !process.HasExited);

if(!process.HasExited)
{
    IntPtr hwnd = process.MainWindowHandle;
    // Do whatever you need to do with hwnd
}