text:
Q: Rails and Mongoid best way to implement sharing system I have to model User and Board in rails using mongoid as ODM.
Each board is referenced to an user through a foreign key user_id and now I want to add the ability to share a board with other users.
Following CRUD I'd create a new Model called something like Share and it's releated Controller with the ability to create/edit/delete a Share but I have some doubts:

*

*First, where to save informations about Shares? I think I may create a field in the Board's collection called shared_with including an array of user ids. in a MySQL I'd created a new table with the ids of who share, the resource shared and the user the resources is shared with but I don't think that's necessary using MongoDB.

*Every user a Board is shared with should be able to edit the Board (but not to delete it) so the Board should have two relations one with the owner and another with the users the board is shared with, right?

*For permission (the owner should be able to delete a board but the users it is shared with shouldn't) what to use? I'm using Devise for authentication but I think something like CanCan would fit better. but how to implement it?

What do you think about this way? Do you find any problems or have better solutions?

A: I generally agree with your solution and I would do the same, i.e. create a separate model called Share, even though it looks like a RDBMS-like solution.
But let's step back and review the available options.
First of all, consider the relations of your models. Draw them on a piece of paper and note the type of relations and their associations (belongs to, has one, has many, has many through or has_and_belongs_to_many). Perfect reference for the associations in rails is http://guides.rubyonrails.org/association_basics.html. Take into account that Mongoid also offers embedded_in/embeds_many type of relations.
In your case the relations would be: User (1..N) Boards for owning, User (N..N) Boards for sharing.
The hint to decide whether to use has_many, has_and_belongs_to_many or embeds_many is whether or not the subordinate model represents semantically embedded type of relation and is not connected with other models than its parent. It it is, use embeds_many, otherwise use has_many or has_and_belongs_to_many.
The hint to decide whether to use has_many :through or has_and_belongs_to_many is whether you are going to add more data to a linking model (Share in your case).
has_and_belongs_to_many in mongoid is doing without creation of a linking model, i.e. board_ids would be kept as an array in the User model and user_ids would be kept as an array in the Board model.
The reason to not use HABTM in your case is simple. You have two relations between your User and Board models (sharing and owning), you would have difficulty in figuring out what expression like user.boards means (shared boards or owned boards). I don't know of an easy way to separate these two kinds of relations without use of a third model (Share) as you proposed in comments (using :as, etc.)
You can also manually keep the ids of boards in your user model, like this:
class User
  include Mongoid::Document
  field :name
  key :shared_board_ids, Array, :index => true
  key :owned_board_ids, Array, :index => true

  def shared_boards
    Board.find shared_board_ids
  end
  # ...

end

However, difficulties in this case arise pretty fast. You have to manually destroy all board references from the User model when you destroy a board. If you keep a sharing_user_ids in your Board model, you have redundancy and another set of difficulties.
So, yes, I would recommend creating a separate Share model, as I show below.
class User
  include Mongoid::Document
  field :name
  has_many :shares
  has_many :boards
end

class Board
  include Mongoid::Document
  field :title
  has_many :shares
  belongs_to :user
end

class Share
  include Mongoid::Document
  belongs_to :user
  belongs_to :board
end

As of permissions, CanCan is simple, but it is doing just fine. Notice a difference between terms authentication (which checks the authenticity of a user, in other words checks that the user is really who he claims he is - normally using password) and authorization (which checks the rights of the user). Authentication is handled by gems like Authlogic, Warden (and Devise based on Warden), Sorcery. Authorization is handled by Declarative_authorization or CanCan.

A: I think you might find better answers on stackoverflow. I'm not an expert in RAILS or mongodb, but I'll try.

*

*Creating a field in the Board's collection would probably work OK.

*You might want to make a single relation collection, and have a type added to the relation. That way you could have multiple owners if you wanted, and you could add more types later, like a 'read only' or a blocked.

*Check the type and render views based on whether or not they are shared to and whether or not they are an owner. I don't think you need a permissions framework for this, but that doesn't mean it's a bad idea to put one in.
Hope that helps!


text:
Q: jQuery on blur not working properly I have a simple educational details page where I am generating textboxes dynamically to enter qualification details. When I try to validate the textboxes, the validation gets fired but not properly. If I try it 2-3 times then it becomes proper. In the first attempt alternate textboxes get validated. When I click on "add row" button a new row gets added but when I try to validate it for 2-3 attempts the validation error is not shown. After few more attempts the validation works. It is all very confusing.
I researched a lot on the internet but could not find any proper solution.
I have pasted my full JSP below. Will be really really thankful for any pointers.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Enter Details</title>

        <link rel="stylesheet" type="text/css" href="../css/jquery.validate.css" />
        <link rel="stylesheet" type="text/css" href="../css/style.css" />

Enter Details

<form id="personalDetails" class="MasterForm" method="post"
    action="AddPersonalDetails.php">

    <input type="button" name="addRow" id="addRow" class="submitbutton" value="Add Row" />

    <input type="submit" name="educational" id="educational" class="submitbutton" value="Submit" />

    Course Name*
    Board / University*
    Marks Obtained*
    Total Marks*
    Percentage*
    Year of Completion*

        <input type="text" name="courseTxt" id="courseTxt" class="validate-text" />
        <input type="text" name="boardTxt" id="boardTxt" class="validate-text" />
        <input type="text" name="marksTxt" id="marksTxt" class="validate-num" />
        <input type="text" name="totalTxt" id="totalTxt" class="validate-num" />
        <input type="text" name="percentageTxt" id="percentageTxt" />
        <input type="text" name="classTxt" id="classTxt" class="validate-text"  />

<input type="hidden" name="countHd" id="countHd" value="1" />
</form>

Thanks in advance.

A: Since you're creating those elements dynamically, try delegating your events:
jQuery(document).on("blur",".validate-text", function (event) {
// repeat for ".validate-num"

Additionally, you shouldn't be using two different versions of jQuery. Remove

A: Instead of using blur .. have you tried using focusout

Read more about focusout here:
http://api.jquery.com/focusout/
major difference between focusout and blur is that blur support event bubbling.

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

it is often used with focusin
an codepen or jsfiddle example would be helpful also

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maths Homework Question Related to Physics This is a physics question, but it's calculations.
A 15kg child slides down a 2.3m -high playground slide. She starts from rest, and her speed at the bottom is 2.1m/s .
What is the change in the thermal energy of the slide and the seat of her pants?
(2.s.f.)
I used the kinematics equation
$$d= \frac{(v_i+v_f)}{2} * (t)$$
$$2.3 = \frac{2.1 \cdot t}{2}$$
$$t= 2.19$$
Then I used t to find acceleration then multiply acceleration with the mass which is 15kg, and then multiply that again by 2.3m to find the change in thermal energy. But I feel like I calculate t incorrectly, because it keeps telling me it's incorrect. The rest is correct, however, the first part is not.

A: The answer to this question is 305m/s but to 2.s.f it is 310m/s

A: It's conservation of energy -- you don't need any calculus. You know that in the absence of friction energy is conserved. If some energy is lost it must have gone to friction -- a.k.a thermal energy. You know how much energy lost because the child starts at some height from rest. That tells you the initial energy (her potential energy.) I think you can take it from there.


text:
Q: Every C++ header in a project as a precompiled header The usual approach is to have one precompiled header in a project that contains the most common includes.
The problem is, that it is either too small or two big. When it is too small, it doesn't cover all the used headers so these have to be processed over and over in every module. When it is too large, it slows down the compilation too much for two reasons:

*

*The project needs to be recompiled too often when you change something in header contained in the precompiled header.

*The precompiled header is too large, so including it in every file actually slows down compilation.

What if I made all of the header files in a project precompiled. This would add some additional compiler work to precompile them, but then it would work very nicely, as no header would have to be processed twice (even preparing the precompiled header would use precompiled headers recursively), no extra stuff would have to be put into modules and only modules that are actually needed to be recompiled would be recompiled. In other words, for extra work O(N) complexity I would (theoretically) optimise O(n^2) comlexity of C++ includes. The precosseor to O(N), the processing of precompiled data would still be O(N^2), but at least minimised.
Did anyone tried this? Can it boost compile times in real life scenarios?

A: With GCC, the reliable way to use precompiled headers is to have one single (big) header (which #include-s many standard headers ...), and perhaps include some small header after the precompiled one.
See this answer for a more detailed explanation (for GCC specifically).

A: My own experience with GCC and Clang with precompiled headers is that you only can give a single pre-compiled header per compilation. See also the GCC documentation, I quote:

A precompiled header file can be used only when these conditions apply:

*

*Only one precompiled header can be used in a particular compilation.

*...

In practice, it's possible to compile every header to a precompiled header. (Recommended if you want to verify if everything is included, not recommended if you want to speed up compilation)
Based on your code, you can decide to use a different precompiled header based on the code that needs to be compiled. However, in general, it's a balancing act between compile time of the headers, compile-time of the CPP files and maintenance.
Adding a simple precompiled header that already contains several standard headers like string, vector, map, utility ... can already speed up your compilation with a remarkable percentage. (A long time ago, I've noticed a 15-20% on a small project)
The main gain you get from precompiled headers is that it:

*

*only have to read 1 file instead of more, which improves on disk access

*reads a binary format that's optimized for reading instead of plain text

*it doesn't need to do all of the error checking as this was already done on creation

Even if you add a few headers that you don't use everywhere, it can still be much faster.
Lately, I also found the Clang build analyzer, it ain't ideal for big projects (see issue on github), though, it can give you some insights on where the time is being spent and what it can improve. (Or what you can improve in the codebase)
In all fairness, I don't use precompiled headers at this point in time. However, I do want to see it enabled on the project I'm working on.
Some other interesting reads:

*

*https://medium.com/@unicorn_dev/speeding-up-the-build-of-c-and-c-projects-453ce85dd0e1

*https://llunak.blogspot.com/2019/05/why-precompiled-headers-do-not-improve.html

*https://www.bitsnbites.eu/faster-c-builds/


text:
Q: how to display custom address field of custom object using aura component
I have followed the steps as per new release about custom address field and created a address data type field in my custom object and then using
<lightning:inputField fieldName="KTDO1__Billing_Location__c" />
This in my lightning recordEditForm but I am unable to see country and state picklist instead its showing text fields.


text: Q: How do I prevent two different accounts from signing in to a website from different tabs of the same browser in php like facebook I trying to develop a website that makes good use of sessions but am having this problem of the session of the second user overriding the session of the first user if I sign in two different accounts on different tabs of the same browser.It is causing my scripts to misbehave. I noticed on facebook that two different accounts can't sign in different tabs of one browser.Any help will be appreciated.


text:
Q: Sankey graphs blank when saved as SVG using plotly for python as the title says whenever I'm saving a Sankey graph no matter if it's large or small it always produces a blank svg. Is there a way to solve this issue? The graph display normally in my jupyter notebook but saves a blank svg (only title is visible).
I'm using plotly 3.6.1
I asked the same question already on the plotly community board, however, there was no response.
def drawSankeyForAreaFlow(area_flow_data, log_index):
sankeyData = getSankeyData(area_flow_data)

data = dict(
    type='sankey',
    node = dict(
      pad = 30,
      line = dict(
        width = 0.5
      ),
      label = ['label 1', 'label 2', 'label 3', 'label 4', 'label 5', 'label 6', 'label 7', 'label 8', 'label 9', 'label 10', 'label 11', 'label 12', 'label 13', 'label 14', 'label 15', 'label 16'],
      color = ['#FF40C5', '#FF4A80', '#FF713D', '#FF9600', '#E5B200', '#A4C700', '#47D400', '#00DB65', '#00DFAE', '#00E1F5', '#00DEFF', '#00D6FF', '#00C7FF', '#58AEFF', '#EA8BFF', '#FF61FF', '#FF40C5']
    ),
    link = dict(
      source = [0, 2, 2, 2, 2, 2, 3, 4, 4, 4, 5, 8, 8, 9, 11, 12, 12, 14, 14, 15, 15, 15, 15, 15],
      target = [2, 4, 5, 11, 12, 15, 9, 4, 12, 15, 2, 2, 4, 0, 3, 0, 2, 8, 14, 0, 4, 12, 14, 15],
      value = [6, 2, 1, 1, 2, 2, 1, 1, 1, 5, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 3, 2, 1, 6]
))

layout =  dict(
    title = "Sankey for log " + str(log_index),
    font = dict(
      size = 10
    )
)

fig=go.Figure(data=[data],layout=layout)
pio.write_image(fig, "./output/graphs/" + "Sankey for log " + str(log_index) + ".svg")
plotly.offline.iplot(fig, validate=False)

return {'sources': sankeyData['sources'], 'targets': sankeyData['targets'], 'values': sankeyData['values']}

allSankeyData = []

for i, log in enumerate(logs):
    allSankeyData.append(drawSankeyForAreaFlow(log["properties"]["area_flow"], i))

A: Plotly doesn't support ANY circular references. At first I thought that was only meant for cases where nodes reference themselves but it appears it's meant also for cases like "A->B, B->A". For some weird reason my sankey graphs still got rendered but they were not saved.


text:
Q: Opening and Viewing "Additional Files" in ArcGIS Layer Package In ArcGIS I've created a layer package with several shapefiles (that include symbology and labels) so I can send it to a coworker. In addition, I've added a spreadsheet document under the "Additional Files" tab (see image below) so my co-worker can cross check it with the attribute table.
My question is, how do my co-worker open or view that spreadsheet from the layer package? When I opened the layer package in ArcMap there is no mentioning of the attachment in any of the menus.
I've researched ESRI's help pages on the subject and none of them specify how to open the additional files, only how to add them.

A: The default location for package install/download is:
"C:\Users\xxxx\Documents\ArcGIS\Packages"
If you browse to that directory in your file explorer you should find the attachments inside of the layer package sub-directory.
Example: If your layer package name was TestPackage the additional files would be located here: "C:\Users\xxxx\Documents\ArcGIS\Packages\TestPackage\commondata\userdata\"


text:
Q: maxmind GeoLiteCity doesn't work properly I'm using maxmind GeoLiteCity to show city name base on user IP address, it show for some of cities but not for all cities.
Here's my code:
I downloaded latest GeoLiteCity.dat  from following link:
http://dev.maxmind.com/geoip/legacy/geolite/
include("geoipcity.inc");
include("geoipregionvars.php");
$ip = $_SERVER['REMOTE_ADDR'];
$gi = geoip_open("GeoLiteCity.dat",GEOIP_STANDARD);
$record= geoip_record_by_addr($gi,$ip);
echo 'City Name: '.$record->city . "\n";
geoip_close($gi);

how to solve it ?
Thanks


text:
Q: $urlProvider not resolvable in controller I can inject $urlProvider in module.config() but when i try to do it in module.controller() I am getting this error:
Unknown provider: $urlRouterProviderProvider <- $urlRouterProvider <- MyCtrl

I have included angular-ui, also imported ui.router in the module.
I cannot see anybody doing this online, but why should it not work?

A: Providers are meant to be configured in the config phase, and then they can be injected into a controller, or the run phase, sans the Provider post-fix:
app.config(function($urlRouterProvider) {
  $urlRouterProvider.deferIntercept();
});

app.run('MyCtrl', function($urlRouter) { // no Provider post-fix
   $urlRouter.listen();
});

See the Angular docs on Providers and the UI-Router's guide on $urlRouterProvider for more information.


text:
Q: Access static class variables in Objective-C I would like to use class variables outside of the class.
By 'outside', I mean the main function where I instantiate the class.
@interface Class: NSObject
static int var_class;   // Class variable
{
    int var_object; // Object variable
}
@end

@implementation Class
@end

In order to access var_object, the object variable, we use:
int main(void)
{
    Class *object = [Class new];

    // Access to the variable
    object->var_object;
    (*object).var_object;

    return 0;
}

I thought I could access var_class, the class variable, in the same way.
But none of them worked. (Unable to compile)
Class.var_class;
// -> Generates error: could not find setter/getter for 'count' in class 'TheClass'

Class->var_class;
// -> Generates error: error: expected '.' before '->' token

How can I get/set the class variable's value?
Declaring a function is the way to access class variables, but I want it simpler.
@interface Class: NSObject
static int var_class;   // Class variable
+(int) get;
+(void) set: (int) val;
@end

@implementation Class
+(int) get
{
    return var_class;
}
+(int) set: (int) val
{
    var_class = val;
}
@end

A: There is no static class variables in Objective-C, thus you can't expect something like Class.var_class. This is why your last proposition is a correct one, and commonly adopted. See, Does Objective-C support class variables?.
----EDIT----
Some new constructions were added to Objective-C, see Objective-C Class Properties. Thus syntax is admitted, while there is no automatic synthesis.


text:
Q: How do I find out if something is using the serial port? I want to program a microcontroller under Debian Wheezy, but can't get it to work so far. I asked on Electrical Engineering and got the advice to check if something is already occupying the serial port. I don't have the program they suggested, brltty.
How can I check if there is some other package preventing the microcontroller board from talking to the computer? Or if there is some kind of driver problem with the device?
This is what happens when I plug it in:
rumtscho@simak:~/Projects/had_launchpad-blink-master$ dmesg | tail
[11936.051300] usb 4-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[11936.051306] usb 4-1: Product: Texas Instruments MSP-FET430UIF
[11936.051313] usb 4-1: Manufacturer: Texas Instruments
[11936.051318] usb 4-1: SerialNumber: 95FF469286C9572A
[11936.060401] cdc_acm 4-1:1.0: This device cannot do calls on its own. It is not a modem.
[11936.060412] cdc_acm 4-1:1.0: No union descriptor, testing for castrated device
[11936.060467] cdc_acm 4-1:1.0: ttyACM0: USB ACM device
[11946.113517] generic-usb 0003:0451:F432.0005: usb_submit_urb(ctrl) failed
[11946.113550] generic-usb 0003:0451:F432.0005: timeout initializing reports
[11946.114261] generic-usb 0003:0451:F432.0005: hiddev0,hidraw0: USB HID v1.01 Device [Texas Instruments Texas Instruments MSP-FET430UIF] on usb-0000:00:1d.0-1/input1

Can I somehow troubleshoot the connection from here?

A: Linux uses ttySx for a serial port device name. For example, COM1 (DOS/Windows name) is ttyS0, COM2 is ttyS1 and so on.

*

*Attach your micro-controller to serial port and type dmesg | grep tty command to check whether it's detected or not.

*If all your slots are PCI, the serial port is likely to be on either an ISA bus or LPC bus (also called a "LPC interface"). LPC is common on laptop computers. Type "lspci" to see if it shows "LPC"
Now for configuring your serial port you have to work with setserial comand. (CLICK HERE to learn setserial command.)
REFERENCES:
http://www.cyberciti.biz/faq/find-out-linux-serial-ports-with-setserial/
http://www.tldp.org/HOWTO/Serial-HOWTO-8.html

A: I'd run lsof as root and then check to see which processes have /dev/tty* files open.  Then trace down the process to determine what they are doing.

A: I use a pc with two external serial controllers to connect in two different BMS systems. Running two vmware players on debian weezy with different Operating systems in each one and connecting one serial port to each vmware machine!
The problem was that unpredictably one or both serials didn't connect to vmware or showed like they were used by another application.
After hours of log searching, hardware changing etc, I noticed in /var/log/syslog the modemmanager making calls to all ttyS* trying to identify connected modem!
I removed it with "apt-get remove modemmanager" and problem solved!
I believe that trying to find connected devices left the ports or the devices connected to the ports in an non ready condition!


text:
Q: Enabling C code to run as C++ code I have a C program that finds duplicate files within a directory. The program is executed on the command line and passed 2 arguments. One is the parent directory, and argument two is the file name. It is working code in c, but I have a GUI and other files for "microservices" written in c++.
How would one call this C code from a c++ file?
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>

//Compile:          gcc dreamduplicatefinder.c -o dreamduplicatefinder.exe
//Run:              ./dreamduplicateFinder.exe parent_dir filename...

#define false 0
#define true  1

int duplicateCount = 0;

int FindDuplicates(char* path, char* fileName);
int CompareFiles(char* originalFile, char* currFile);

int main(int argc, char *argv[])
{
    //Two additional arguments are expected: Parent dir, file to find duplicates of...

    if (argc != 3)
    {
        printf("Usage: %s 'Base Directory' 'File Name'\n", argv[0]);
        return -1;
    }

    //argv[1] = base dir, argv[2] = file to find duplicates of; e.g argv[1] = /home,
    //argv[2] = "file.txt"...

    FindDuplicates(argv[1], argv[2]);
    printf("\n\nFound %d duplicate(s)\n", duplicateCount);
    return 0;
}

int FindDuplicates(char* path, char* fileName)
{
    DIR *dir;
    struct dirent *dp;
    struct dirent *result;
    struct stat statp;

    char absoluteFilePath[255];

    if ((dir = opendir(path)) == NULL)
    {
        //printf(dir);                  //error could becuase trying to open shortcut or corrupt folder.
        printf("%s\n",path);
        perror("Failed to open directory");

        return -1;
    }

    while ((dp = readdir(dir)) != NULL)
    {
        //readdir returns . and .. which we should ignore...
        if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, ".."))
        {
            //find file full path, relative to base path. e.g, a /home/file.txt...

            //copy path to absoluteFilePath...
            strcpy(absoluteFilePath, path);

            //append / at end...
            strcat(absoluteFilePath, "/");

            //append filename to path...
            strcat(absoluteFilePath, dp->d_name);

            //check if the current file is actually file or dir...
            stat(absoluteFilePath, &statp);

            if (S_ISDIR(statp.st_mode))     //is a directory...
            {
                //recurse through this dir...
                FindDuplicates(absoluteFilePath, fileName);
            }
            else if (S_ISREG(statp.st_mode))    //is a file...
            {
                //check for duplicates here...
                //compare current file with the file specified by user...

                if (strcmp(fileName, absoluteFilePath))
                {
                    if (CompareFiles(fileName, absoluteFilePath))
                    {
                        //yes, duplicate; print it...
                        printf("%s\n", absoluteFilePath);
                        duplicateCount++;
                    }
                }

            }       //end else if (S_ISREG(statp.st_mode))...

        }       //if (strcmp(dp->d_name, ".") && strcmp(dp->d_name,".."))...
    }       //end while...

    closedir(dir);
    return 0;

}

int CompareFiles(char* originalFile, char* currFile)
{
    //two step comparison: (1) first check size; if not same, return false.
    //If equal, (2) compare file content.If equal, return true, false otherwise...

    struct stat statOriginal, statCurr;
    stat(originalFile, &statOriginal);
    stat(currFile, &statCurr);

    //Step 1...
    if ((int)statOriginal.st_size != (int)statCurr.st_size)  //size not same...
        return false;

    //Step 2...
    //size matches, files can be same; confirm it by matching both file contents...

    int fdOriginal = open(originalFile, O_RDONLY);
    int fdCurr = open(currFile, O_RDONLY);

    if (fdOriginal == -1 || fdCurr == -1)
        return false;       //error occurred, not sure if file is duplicate...

                            //we will read file in small chunks and compare...

    int chunkSize = 1024, bytesRead;
    char *bufferOriginal = (char*)malloc(chunkSize * sizeof(char));
    char *bufferCurr = (char*)malloc(chunkSize * sizeof(char));

    while (true)
    {
        //read file in chunk...
        bytesRead = read(fdOriginal, bufferOriginal, chunkSize);
        if (bytesRead <= 0)
            break;      //end of file...

        bytesRead = read(fdCurr, bufferCurr, bytesRead);

        //compare buffer...
        if (strcmp(bufferOriginal, bufferCurr))     //if content not matching...
            return false;
    }

    return true;
}

My errors include: (from compareFiles function)
2x  'open' identifier not found
2x  'read' identifier not found
The working code for those curious.
Thank you @MarcusMüller & @JesperJuhl
#include "stdafx.h"             //there is nothing in this header

#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
    //Compile:          gcc <name of this file>.cpp -o <nameOfThisFile>.exe
    //Run:              <nameOfThisFile> parent_dir filename...

#define false 0
#define true  1

    int duplicateCount = 0;

    int FindDuplicates(char* path, char* fileName);
    int CompareFiles(char* originalFile, char* currFile);

    int main(int argc, char *argv[])
    {
        //Two additional arguments are expected: Parent dir, file to find duplicates of...

        if (argc != 3)
        {
            printf("Usage: %s 'Base Directory' 'File Name'\n", argv[0]);
            return -1;
        }

        //argv[1] = base dir, argv[2] = file to find duplicates of; e.g argv[1] = /home,
        //argv[2] = "file.txt"...

        FindDuplicates(argv[1], argv[2]);
        printf("\n\nFound %d duplicate(s)\n", duplicateCount);
        return 0;
    }

    int FindDuplicates(char* path, char* fileName)
    {
        DIR *dir;
        struct dirent *dp;
        struct dirent *result;
        struct stat statp;

        char absoluteFilePath[255];

        if ((dir = opendir(path)) == NULL)
        {
            //possibly trying to open shortcut or corrupt folder typically.
            printf("Failed to open directory %s \n",path);
            return -1;
        }

        while ((dp = readdir(dir)) != NULL)
        {
            //readdir returns . and .. which we should ignore...
            if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, ".."))
            {
                //find file full path, relative to base path. e.g, a /home/file.txt...

                //copy path to absoluteFilePath...
                strcpy(absoluteFilePath, path);

                //append / at end...
                strcat(absoluteFilePath, "/");

                //append filename to path...
                strcat(absoluteFilePath, dp->d_name);

                //check if the current file is actually file or dir...
                stat(absoluteFilePath, &statp);

                if (S_ISDIR(statp.st_mode))     //is a directory...
                {
                    //recurse through this dir...
                    FindDuplicates(absoluteFilePath, fileName);
                }
                else if (S_ISREG(statp.st_mode))    //is a file...
                {
                    //check for duplicates here...
                    //compare current file with the file specified by user...

                    if (strcmp(fileName, absoluteFilePath))
                    {
                        if (CompareFiles(fileName, absoluteFilePath))
                        {
                            //yes, duplicate; print it...
                            printf("This is a duplicate! %s\n", absoluteFilePath);
                            duplicateCount++;
                        }
                    }

                }       //end else if (S_ISREG(statp.st_mode))...

            }       //if (strcmp(dp->d_name, ".") && strcmp(dp->d_name,".."))...
        }       //end while...

        closedir(dir);
        return 0;

    }

    int CompareFiles(char* originalFile, char* currFile)
    {
        //two step comparison: (1) first check size; if not same, return false.
        //If equal, (2) compare file content.If equal, return true, false otherwise...

        struct stat statOriginal, statCurr;
        stat(originalFile, &statOriginal);
        stat(currFile, &statCurr);

        //Step 1...
        if ((int)statOriginal.st_size != (int)statCurr.st_size)  //size not same...
            return false;

        FILE* fdOriginal;
        if (fdOriginal = fopen(originalFile, "r")) {
            if (fdOriginal == NULL) { fputs("File error", stderr); return false; }
        }
        else return false;        //error occurred, not sure if duplicate
        FILE* fdCurr;
        if (fdCurr = fopen(currFile, "r")) {
            if (fdCurr == NULL) { fputs("File error", stderr); return false; }
        }
        else return false;

        int chunkSize = 1024, objsRead;
        char *bufferOriginal = (char*)malloc(chunkSize * sizeof(char));
        if (bufferOriginal == NULL) { fputs("Memory error for buff orig", stderr); exit(2); }

        char *bufferCurr = (char*)malloc(chunkSize * sizeof(char));
        if (bufferCurr == NULL) { fputs("Memory error for buff curr", stderr); exit(2); }

        while (true)
        {
            //read file in chunk...
            //std::size_t fread( void* buffer, std::size_t size, std::size_t count, std::FILE* stream );
            objsRead = fread(bufferOriginal, sizeof(char), chunkSize , fdOriginal);
            if (objsRead <= 0)
                break;      //end of file...

            objsRead = fread(bufferCurr, sizeof(char), objsRead, fdCurr);

            //compare buffer...
            if (strcmp(bufferOriginal, bufferCurr))     //if content not matching...
                return false;
        }

        return true;
    }

A: You usually just wouldn't do that. You'd wrap it in a C function, and compile it to an object file.
Then you'd include your C header with extern "C" {…}, and just call that function from C++.
When building your executable, you'd link in the object file containing your C function. Done!
Note: C isn't C++, and albeit your code not being illegal in C++ (as far as I can instantly tell), it does very "ugly" things (like #defineing true and false – ugh, that would already be a bad idea in C, to be honest). So, deal with it like you would deal with code in Fortran, or Java, or any other language that has a calling convention that you can use from C++ (which, usually, is the C calling convention): Just use it as an extern object.

A: Using ::open and ::read should cause the functions to be found.
You may also want to replace the C headers (like "string.h") with their C++ equivalent versions (like "cstring").
Your defines for true and false should also go. In C++ those are proper bools, not integers. This means the return type of CompareFiles should be changed to bool.
And you should wrap duplicateCount in an anonymous namespace - or return it from the function that updates it (either by returning a small struct with two ints, or by using a std::pair or std::tuple) - global variables are evil.


text:
Q: Calculate average latitude and longitude in C# I have (minLatitude,maxLatitude) and (minLongitude,maxLongitude) pairs in decimal degrees, and I need to calculate the mean point of the box those pairs define, how can I get their average latitude/longitude? I get a pretty big offset when the simple arithmetic mean is calculated.
Thanks!

A: The solution suggested by Pierre-Luc Champigny is wrong.
In the image bellow you can see two lines:

*

*(lat1,lon1) --> (lat2,lon2)

*(lat1,lon2) --> (lat2,lon1)

Half length of each line in green, the other half in blue.
You can see that the center of both lines is not the same point, and both centers are not the center of the polygon.

In order to find the center of the polygon:

*

*lat= avrg(lat1,lat2)

*lon= avrg(lon1,lon2)

To get these values you can use the link suggested by Pierre-Luc Champigny, but:

*

*Take the lat of the midpoint of (lat1,lon1) --> (lat2,lon1)

*Take the lon of the midpoint of (lat1,lon1) --> (lat1,lon2)

A: From: http://www.movable-type.co.uk/scripts/latlong.html
Your values should be all in radian, so using the midpoint formula:
var lat1 = minLatitude;  // In radian
var lat2 = maxLatitude;  // In radian
var lon1 = minLongitude; // In radian
var lon2 = maxLongitude; // In radian

var dLon = (lon2-lon1);

var Bx = Math.Cos(lat2) * Math.Cos(dLon);
var By = Math.Cos(lat2) * Math.Sin(dLon);
var avgLat = Math.Atan2(
           Math.Sin(lat1) +
           Math.Sin(lat2),
           Math.Sqrt((
           Math.Cos(lat1)+Bx) * (Math.Cos(lat1)+Bx) + By*By));

var avgLong = lon1 + Math.Atan2(By, Math.Cos(lat1) + Bx);


text:
Q: Why margin-right is longer than others even when percentage is used HTML code :

CSS :
.box {
width: 50%;
margin: 10%;
padding: 10%;
border: 2px dotted grey;
border-radius: 5px;}

OUTPUT :

in the Developers console, the computed CSS value of margin is same on all the sides.
But it seems a little off from the right? What could be the problem??

A: Youir margin: 10% is causing the issue. Change it to margin: 10% auto;. So it centers perfectly. That's it!
.box {
  width: 50%;
  margin: 10% auto;
  padding: 10%;
  border: 2px dotted grey;
  border-radius: 5px;
}

A: If you sum up the width and the margins, you come to the result 70%. The left margin is used, because your elements are floated left. This means that on the right side, after 10% left margin and 50% width, still 30% are left. Thats why the margin on the right looks bigger.
You could use a margin of 25% on the left or center the boxes in order to be centered. Or another approach: set margin left and right to auto.

A: This is not about margin-right is longer. This is about all element are left aligned.
You can set the margin property to auto in .box to horizontally center the element .
margin: 10% auto;

The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
Updated snippet :-

.box {
width: 50%;
margin: 10% auto;
padding: 10%;
border: 2px dotted grey;
border-radius: 5px;}


text:
Q: Computing skewness and kurtosis in presto Does presto have built in function to compute skewness and kurtosis?  I know presto has built in functions to compute mean and variance.  If not, how should I compute these functions within presto?

A: Yes, Presto has both skewness and kurtosis.  See the docs for aggregate functions: https://prestodb.io/docs/current/functions/aggregate.html


text:
Q: Rails - Override primary key on has_one I have the following associations, basically I want to link via userid and not the id of the object.
class Tweet < ActiveRecord::Base
  has_one :user_profile, :primary_key => 'userid', :foreign_key => 'twitter_userid'

class UserProfile < ActiveRecord::Base
  belongs_to :tweet, :foreign_key => 'userid'
However the following spec fails as twitter_userid is reset to the id of the object

it "should have the user's twitter id set on their user profile" do
   t = Tweet.new(:twitter_id => 1,
                  :status => 'Tester',
                  :userid => 'personA',
                  :user_profile => UserProfile.new(:twitter_userid => 'personA', :avatar => 'abc'))
   t.save!
    t.user_profile.twitter_userid.should == 'personA'
 end

should have the user's twitter id set on their user profile
expected: "personA",
    got: 216 (using ==)
However, the following does pass:

 it "should return the correct avatar after being saved" do
   t = Tweet.new(:twitter_id => 1,
                  :status => 'Tester',
                  :userid => 'personA',
                  :user_profile => UserProfile.new(:twitter_userid => 'personA', :avatar => 'abc'))
   t.save!

   t.user_profile.avatar.should == 'abc'
 end

How can I force it to use userid and not id?
Thanks
Ben

A: There are two things going on here. I think you have switched the :has_one and :belongs_to declarations.
The :belongs_to comes in the model that has the foreign-key.
The :has_one comes in the model that is referred to (if it is only one, otherwise if many rows :belong_to the same, it is a has_many of course). For more info read here.
First, you will need to specify (overrule) the primary key of the model. Here i am assuming a user can have many tweets instead of just one (otherwise replace by :has_one).
class UserProfile
  set_primary_key :userid
  has_many :tweets
end

then you need to adjust your :has_one declaration:
class Tweet
  belongs_to :user_profile, :foreign_key => :userid
end

Then, secondly, once your relations are setup correctly, there is no need to assign both :user_profile or :userid at creation time. Either you create a new UserProfile and the foreign-keys will automatically by correct, or you assign an userid of an existing profile.
Hope this helps.

A: cite@antiope:/tmp/foo$ script/console
Loading development environment (Rails 2.3.4)
>> t = Tweet.new(:twitter_id => 1,
?>                   :status => 'Tester',
?>                   :userid => 'personA',
?>                   :user_profile => UserProfile.new(:twitter_userid => 'personA', :avatar => 'abc'))
=> #<Tweet id: nil, twitter_id: 1, status: "Tester", userid: "personA", created_at: nil, updated_at: nil>
>> Tweet.set_primary_key :userid
=> nil
>> t.save
  Tweet Create (0.4ms)   INSERT INTO "tweets" ("created_at", "updated_at", "userid", "twitter_id", "status") VALUES('2009-09-10 20:19:36', '2009-09-10 20:19:36', 'personA', 1, 'Tester')
  UserProfile Create (0.1ms)   INSERT INTO "user_profiles" ("twitter_userid", "created_at", "updated_at", "avatar") VALUES('personA', '2009-09-10 20:19:36', '2009-09-10 20:19:36', 'abc')
=> true
>> Tweet.set_primary_key :id
=> nil

Modfiying the model a split second before saving it  might be an acceptable solution if you only have to redefine the primary key in one place (I didn't test if modifying the Tweet class like that affected only the current controller or all actions). Still, it's only what I consider to be a workaround.

A: If the primary key on your db is not called id then you want to do something like this:
class Tweet < AR:B
  set_primary_key "userid"
end

However, I'm not sure I totally understand the question.  Is there a reason you want to step outside of the rails conventions?

A: I think this is probably the most practical way.  I don't think it is possible in Rails otherwise:
http://compositekeys.rubyforge.org/


text:
Q: What is the minimal agent install footprint for Delphi build automation? When creating a build server that does clean version control check-outs and full system builds of everything in a given source repository or project, what is the minimum required Delphi install footprint for XE3 Win32/Win64 projects?  (Core system - not 3rd party components)
I'd prefer to have a small subset of files that can be included in a repository rather than a full Delphi install.

A: Found a source for D2006+D2007:
https://delphi.fandom.com/wiki/Setting_up_a_Delphi_Build_Machine

A: Using the command line compilers, you do not need to install the IDE on the remote agent computer. From a running installation, copy the \Bin and \Lib sub-folder content into your remote agent.
Then run DCC32.exe command line compiler, changing the DCC32.CFG file content to point to all needed source code paths. Do not forget to set a temporary folder for all your .dcu generated files, and specify a .exe destination folder.
See

*

*How do I compile my delphi project on the command line?

*and the official documentation of the command-line compiler.

Update: Yes, I know, MSBuild is the "official way". But for a build agent, I found out how easier it is to work with the command line compiler. And the question here is about the "minimal footprint" to build Delphi apps.
With DCC32, nothing to install, no need to reproduce the same layout than the one in the IDE. Build environment should not be tied to the IDE configuration, and should be "clean" from any developer specificity, from my experiment. It should build from scracth and from source all your application, run the unit tests, and prepare the release. I've seen some .dcu or .bpl polluting the build process, taking hours to find out why a code modification did not be taken in account!
If you need some complex build process, I always prefer to code some lines of Delphi (or python), reading the configuration from text files, regardless of the computer the build agent runs on. It is a PITA to install Delphi on a computer just for a build (especially latest versions), and even if the license allows you to do so, whereas the command-line compiler is safe and fast to install/setup. Just copy the files, and run them. If your build agent is a virtual server (as it should be today), your IT will be pleased not to pollute the registry. If just your company IT would prefer Delphi because of its cleanness in regard to other frameworks, it is always worth it.


text:
Q: Should RouteConfig.cs be static class By Defualt, when you create a new ASP.Net MVC app, the RouteConfig is not a static class but the only method it has "RegisterRoutes" is a static method.
When I analyse my code using SonarQube, the tool suggests the following for RouteConfig.cs
Add a "protected" constructor or the "static" keyword to the class declaration
So, should I make the class static?

A: Whether the class is static or not will not change the behavior of the application. So if it is for making your code analysis tool happy, go ahead, make it static.


text:
Q: Why does the webcam image appear darker than when it's started from another application? I am using the Windows API to take a picture with the attached webcam.
All works fine except the picture captured is very dark. If I start the webcam in another application and then I capture with my application, all works fine. What am I doing wrong?
Here is the code I use:
procedure TWebCam.Execute; //different thread
var
  hand: THandle;
  fname: AnsiString;
const
  WM_CAP_START = $0400;
  WM_CAP_DRIVER_CONNECT = $0400 + 10;
  WM_CAP_DRIVER_DISCONNECT = $0400 + 11;
  WM_CAP_SAVEDIB = $0400 + 25;
  WM_CAP_GRAB_FRAME = $0400 + 60;
  WM_CAP_STOP = $0400 + 68;
  WM_CAP_SET_PREVIEW = WM_CAP_START + 50;
  WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52;
  WM_CAP_SET_SCALE = WM_CAP_START + 53;
begin
  FreeOnTerminate := True;
  fname := AnsiString(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) +
    'capture.bmp');
  if FileExists(String(fname)) then DeleteFile(string(fname));
  hand := capCreateCaptureWindowA('CapWindow32', WS_CHILD and WS_VISIBLE, 0, 0,
    0, 0, frmMain.Handle, 0);
  if hand <> 0 then
  begin
    if SendMessage(hand, WM_CAP_DRIVER_CONNECT, 0, 0) <> 0 then
    begin
      SendMessage(hand,WM_CAP_SET_PREVIEWRATE,66,0); //tried some stuff that are not required but without any success
      SendMessage(hand, WM_CAP_SET_PREVIEW, 1, 0);
      Sleep(5000);
      SendMessage(hand, WM_CAP_GRAB_FRAME, 0, 0);
      SendMessage(hand, WM_CAP_SAVEDIB, 0, NativeInt(PAnsichar(fname)));
      SendMessage(hand, WM_CAP_DRIVER_DISCONNECT, 0, 0);
      SendMessage(hand, $0010, 0, 0);
      SendMessage(frmMain.Handle,WM_USER + 24,0,0); //notify main thread
    end
    else
    begin
      SendMessage(hand, $0010, 0, 0);
      Synchronize(NoWebcam);
    end;
  end
  else
    Synchronize(NoWebcam);
end;

A: I hate to give my own questions an answer but maybe someone will find it useful in the future.
The thing is that the webcam adjusts its luminosity progressively when it starts, so you must first capture some dummy frames to get a normal picture... Here is what I use now:
var
 i : Integer;
...
begin
...
   for i := 0 to 24 do
   begin
     SendMessage(hand, WM_CAP_GRAB_FRAME, 0, 0);
     Sleep(200)
   end;
...
end;

Works like a charm, kind of hacky, I wish a WaitForInputIdle function exist for devices too...


text:
Q: Undefined symbols for architecture armv7 This problem has been driving me crazy, and I can't work out how to fix it...
    Undefined symbols for architecture armv7:
  "_deflateEnd", referenced from:
      -[ASIDataCompressor closeStream] in ASIDataCompressor.o
  "_OBJC_CLASS_$_ASIDataDecompressor", referenced from:
      objc-class-ref in ASIHTTPRequest.o
  "_deflate", referenced from:
      -[ASIDataCompressor compressBytes:length:error:shouldFinish:] in ASIDataCompressor.o
  "_deflateInit2_", referenced from:
      -[ASIDataCompressor setupStream] in ASIDataCompressor.o
ld: symbol(s) not found for architecture armv7
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1

I think it has to do with:
ld: symbol(s) not found for architecture armv7

But I have added: libz.1.2.3.dylib and it's not helping, anyone got any ideas?

A: There is usually a alias without the version identifier that is linked to the current version, in this case libz.dylib is linked to libz.1.2.5.dylib.  Use the base alias instead of the versioned one.

A: I had the same problem when I use admob library, I fixed it changing "Architectures" to "Standard architectures armv7, armv7s" without including 64-bit.

A: Common Causes
The common causes for "Undefined symbols for architecture armv7" are:

*

*You import a header and do not link against the correct library. This is common, especially for headers for libraries like QuartzCore since it is not included in projects by default. To resolve:

*

*Add the correct libraries in the Link Binary With Libraries section of the Build Phases.

*If you want to add a library outside of the default search path you can include the path in the Library Search Paths value in the Build Settings and add -l{library_name_without_lib_and_suffix} (eg. for libz.a use -lz) to the Other Linker Flags section of Build Settings.

*You copy files into your project but forgot to check the target to add the files to. To resolve:

*

*Open the Build Phases for the correct target, expand Compile Sources and add the missing .m files. If this is your issue please upvote Cortex's answer below as well.

*You include a static library that is built for another architecture like i386, the simulator on your host machine. To resolve:

*

*If you have multiple library files from your libraries vendor to include in the project you need to include the one for the simulator (i386) and the one for the device (armv7 for example).

*Optionally, you could create a fat static library that contains both architectures.

Original Answer:
You have not linked against the correct libz file. If you right click the file and reveal in finder its path should be somewhere in an iOS sdk folder. Here is mine for example

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/lib

I recommend removing the reference and then re-adding it back in the Link Binary With Libraries section Build Phases of your target.

A: Under Target -> Build Settings -> Apple LLVM compiler language:
setting 'C++ Language Dialect' and 'C++ Standard Library' to Compiler default helped solve it.

A: I only added the libz.1.2.5.dylib to my project and it worked like a charm.
Steps -

*

*Go to Build Phases.

*Link Binary With library - use the '+' button to choose frameworks and libraries to add.

*Select libz.1.2.5.dylib from the list.

*Build and run.

A: I had a similar issue and saw errors related to "std::"
I changed Build Settings -> Apple LVM 5.0 - Language C++ -> C++ Standard Library
from libc++ (LLVM C++ Standard Library with C++11 support)
to libstdc++ (GNU C++ Standard Library)

A: If you have the flag -ObjC under your Target > Build Settings > Other Linker Flags and you're getting this issue, consider removing it. If you intentionally added it because you need to load some Obj-C code from a static library that wouldn't normally be loaded otherwise, IE, an Obj-C category, then you should use -force_load <path> instead of -ObjC.
<path> should be relative to your Xcode project directory. IE, if your directory structure looks like this:
iOSProject
  + iOSAPI.framework
      + iOSAPI
  + iOSAPI.xcodeproj

Then you should have this flag set for Other Linker Flags:
-force_load iOSAPI.framework/iOSAPI

If you want to include multiple libraries like that, then you should include a separate -force_load line for each of them.
-force_load iOSAPI.framework/iOSAPI
-force_load another.framework/another

A: Here's how I got this problem:
I added a .h, .m and NIB from another project by dragging them onto my project navigator. Xcode didn't add them to the Build Phases properly.
Check my answer because I had a similar problem that I was able to solve by doing some steps.

A: Probably some classes are missing from your target. This usually happens when you rename/remove/add new classes files to your project. To fix add the newly added classes to some targets.
Select the class in the Project Navigator (right sidebar) , open the Utilities sidebar (right sidebar), from the Utilities select the File Inspector (file like icon), under the Target Membership tab tick your targets. This is all to avoid the "Remove reference" and add again with ticking "Add to targets" trick.
So: Select Class -> Utilities (File Inspector) -> Target Membership -> Tick the targets you want.

A: I have have multiple @interfaces in the .h file and hadn't yet included the all of the corresponding @implementation directives. Make sure that they are all balanced out.

A: I had a similar issue and I had to check "Build Active Architecture Only" on each of the Project configurations (Debug, Release and Deployment) and in the Build Settings of the Target.

A: if you're dealing with the iOS5 upgrade, I found that for compiling a project written to target 4.3, I could just rename libz.1.2.3.dynlib in the Project Navigator to libz.1.2.5.dynlib and it compiled.
My iPhoneOS50SDK/usr/lib folder has no libz.1.2.3.dynlib--don't know whether it's a beta thing or just natural upgrade.

A: Go to your project, click on Build phases, Compile sources, Add GameCenterManager.m to the list.

A: This fixed my problem: The dependency I am using is not supporting armv7. So I had no other option than to remove it. Armv7 is used for only very old iphones anyway (like iphone 4).

*

*Go 'Build Settings / All'

*Set 'Valid Architectures' to 'arm64 arm64e'

A: Another possible cause of "undefined symbol" linker errors is attempting to call a C function from a .mm file.  In this case you'll need to use extern "C" {...} when you import the header files.
Linker error calling C-Function from Objective-C++

A: I didn't find this suggestion here so here it goes:
if your project has more than one target (ie one for OSX and one for iOS) then you must link the relevant libraries for each target.. so for example in my case I needed AudioToolbox.. I had to add it once for OSX and once for iOS (under the frameworks folder, you must have a duplicate of each library for each target.. if you see only one.. then that's a red flag)

A: I was facing an issue with PJSIP libraries,
Tried the following in other linker flags in project and able to resolve the error:
-framework
Foundation
-framework
UIKit
Above linker flags are used in Siphone Project over github. These settings will help you resolve problems related to linking of C++ libraries.

A: I had a similar issue last night and the problem, was related to the fact that I had dragged a class from the Finder to my project in Xcode.
The solution was to go the the Build Phases tab and then the Compile Sources and make sure you drag the class to the list.

A: I had a similar issue with that. The class name after _OBJC_CLASS_$_ was actually my class. The reason was I didn't tick "Add to Target" when I drag the source code files into navigation list.
My solution was:

*

*delete the class from the navigation list and choose "remove reference only"

*drag the source code files again and make sure the tick box for "add to Target" is ticked. The tick box is just under "Copy if needed" and "Create group".

A: Finally i've figured it out, I solved this issue by adding absent framework to target->Build Phases->Link Binary With Libraries

A: I once had this problem. I realized that while moving a class, I had overwritten the .mm file with .h file on the destination folder.
Fixing that issue fixed the error.

A: I received the 'Undefined symbols for architecture armv7:' error when trying to compile a project that had the target build setting for 'C++ Standard Library' set to 'libc++' (necessary as the project was using some features from C++ 11), and the project included a sub-project that had the same setting set to 'libstdc++' (or compiler default as it is currently).
Changing the sub-project's 'C++ Standard Library' setting to libc++ fixed it, but only after first setting the deployment target for the sub-project to 5.0 or above (5.0 is necessary for libc++).

A: I give you more suggestions that you can check when other common suggestions are not help.
If you link with other project(libxxx.a) you might sometimes meet strange problem which you can find the symbol with tools like nm but they just can not find the symbols in ld. Then you should check if the two projects are built in the same flags, some of them may affect the binary format.

*

*check c++ compiler.

*check c++ dialect setting.

*check c++ runtime type support. (-frtti/-fnortti)

*check if there is .a with the same name appears elsewhere, could be beyond the wanted file in the link path list. remove them.

A: I got this problem when I run app on iphone5s, it was solved by add arm64 to Architectures.

A: I had the same problem. I tried every thing from the huge list of answer but in the end my problem was:
I'm working with openCV so I need to combine C++ code in my code. To do this you should change the files which use objective-c and C++ to .mm
I didn't changed one file and this file has no connection to the C++ code but I had to change it.

A: I had this issue, when installing shareKit. It worked in the simulator, but not on the device. I removed -all_load from the Other Linker Flag and everything works fine in both simulator and iphone device.

A: In my case, I'd added a framework that must be using Objective C++. I found this post:
XCode .m vs. .mm
that explained how the main.m needed to be renamed to main.mm so that the Objective-C++ classes could be   compiled, too.
That fixed it for me.

A: I use to face that issue when the module (file .m) is not in the target that I am working with.

A: For me the problem was that i forget to set value for my constants in the .m (implementation)
file const kFooKey = @"Foo";

A: I also added files through Dragging and Dropping. What I did, I removed references of all the files (Excluding frameworks) then added them again properly via Add Files To Project option, problem gone.

A: If you're building from Unity3D 5 and also using a Prime31 plugin and you're getting this error it's probably due to a duplicate .dll. If you look through your warnings in Unity's editor one of them will tell you this and warn that it could cause build errors. To see if this is the case, type P31 in your project search field and it should pop right up, maybe even more than one. The duplicate's will have a ' 1' at the end of the file name. This is probably caused from updating the plugin in editor via the store or the Prime31 menu tab.

A: For what it is worth, mine was fixed after I went to target->Build Phases->Link Binary With Libraries, deleted the libstdc++.tbd reference, then added a reference to libstdc++.6.0.9.tbd.

A: I was facing the same problem when I included one third party framework.
The issue got resolved when I removed armv7s from the Valid Architectures entry in Build Settings of the target, it starts working.

A: rename your m file (which includes methods funcs) to mm or vice versa will fix your problem.
mine solved renaming mm to m
or m to mm.

A: Try to implement at least one non-inline function of your derived class. If you don't do this, the linker might avoid creating type info for that class.

A: In Xcode Version 6.3.2 , I solved the exactly same problem by adding Library
libxml2.dylib and libz.dylib In Link Binary With Libraries !

A: In my case, I had a similar problem when I created a new branch under source control.
I was able to resolve this problem by simply going Product>Clean

A: I had this warning, when wrote two classes in .h file of another class, but FORGOT to write the implementation for this classes in .m file.

A: Go TARGETS -> General -> Deployment Info -> set Target 8.1 or 10.0
Framework or Library have no ARMV7 Architecture.

A: If you faced this issue with your Flutter project while building in Release mode - that's what helped me:

*

*Set your build system to New Build System in File > Project Settings…

*delete folders ios and build_ios from your project folder.

*create ios module by executing flutter create . from your project folder.

*open Xcode and:

*

*set the IOS Deployment Target to at least 9.0 in PROJECT > Runner

*check your Signing &  Capabilities

*make sure your Build Configuration is set to Release in Edit Scheme... and build for Generic iOS Device

*execute pod install from your project folder

*execute flutter pub get from your project folder

now open your Xcode and build or archive it: Product > Build (or Archive)


text:
Q: Как получить данные из JSON и сохранить их в базу данных? Имеется json строка следующего вида:
{"status":{"timestamp":"2021-05-03T16:47:16.362Z","error_code":0,"error_message":null,"elapsed":370,"credit_count":0,"notice":null},"data":{"2016-10-26T02:39:28.000Z":{"BTC":[1],"USD":[660.28167725,87283944,10525640015.288086]},"2016-10-27T02:39:28.000Z":{"BTC":[1],"USD":[702.39459229,89816296,11200777509.550781]}}}

Как получить из нее данные из data?
Интересует сама дата, USD в 3 вариантах.

Пробовал так, но не смог вытянуть нужное:
$json = file_get_contents($json_url);
$data = json_decode($json);

foreach ($data as $item) {
    echo $item->USD;
}

Результат:
stdClass Object
(
[status] => stdClass Object
    (
        [timestamp] => 2021-05-03T16:47:16.362Z
        [error_code] => 0
        [error_message] =>
        [elapsed] => 370
        [credit_count] => 0
        [notice] =>
    )

[data] => stdClass Object
    (
        [2016-10-26T02:39:28.000Z] => stdClass Object
            (
                [BTC] => Array
                    (
                        [0] => 1
                    )

                [USD] => Array
                    (
                        [0] => 660.28167725
                        [1] => 87283944
                        [2] => 10525640015.288
                    )

            )

        [2016-10-27T02:39:28.000Z] => stdClass Object
            (
                [BTC] => Array
                    (
                        [0] => 1
                    )

                [USD] => Array
                    (
                        [0] => 685.96984863
                        [1] => 93600296
                        [2] => 10936274615.024
                    )

            )

A: Проще преобразовать в массив, добавив true как второй аргумент в json_decode, а дальше примерно так
$data = json_decode($json, true);
foreach($data['data'] as $datetime => $v) {
   foreach($v['USD'] as $val) {
      echo "$datetime $val<br>\n";
   }
}


text:
Q: Using Mustache with joomla I am trying to use Mustache.php with Joomla. What I would like it to do is check the whole page for the curly brackets and then change {{name}} for PERSONS NAME etc etc. I have tried playing around with it with the example they have on the website and have got the hello world to echo at the top of the page like the example, the thing is if I include the {{planet}} anywhere else on the page it just literally echo's {{planet}} , how can I get it to render the whole page and search for any instances of {{planet}} and replace it with world, so that I can include {{name}} in templates etc  ?.
This is the example I have put into my site templates index.php, im not sure how to direct it to render the whole page though, does anyone know if joomla stores the whole page in an array before its displayed or a way to do the above ?.
<?php
include('Mustache.php');
$m = new Mustache;
echo $m->render('Hello {{planet}}', array('planet' => 'World!'));
// "Hello World!"
?>

A: I think you need to reverse how you're thinking about this. Instead of searching the page for instances of Mustache, you should pass the contents of the page to Mustache to render. It may be easier to store the contents in a separate template file.
<?php
include('Mustache.php');
$m = new Mustache;

$tmpl = "Content to display like Hello {{planet}}";

$view_data = array('planet' => 'World!');

echo $m->render($tmpl, $view_data);

How you manage storing and retrieving templates is up to you.


text:
Q: How to handle null return from Kotlin's find function? I have a list of objects, for example:
val companies = listOf(
        Company(id = "1", name = "IBM"),
        Company(id = "2", name = "Apple"))

Next, I want to find an object from this list by name condition and get the value of an id field of the object found. So, I'm using find function calling on the list:
val companyId = companies.find { it.name == "IBM" }.id

But this one doesn't compile with Only safe or non-call calls are allowed on a nullable receiver. So, how should I handle the possible null return from find? I tried with an Elvis operator to return an empty String otherwise, like:
val companyId = companies.find { it.name == "IBM" }.id ?: ""

But that still doesn't compile.

A: Change it to (because it cannot get the id from a null object unless you handle it as nullable (String?) again):
val companyId = companies.find { it.name == "IBM" }?.id ?: ""

If you are sure that there is a company with name "IBM" you can use !! (not recommended):
val companyId = companies.find { it.name == "IBM" }!!.id

further more


text: Q: Start Glassfish 6.2.1 in netbeans 14 with jdk 18 I'm trying to make a web application in the netbeans ide, after writing my code and running the project I get the error "Glassfish server could not be started with JDK 18 (Default). Please select another Java SE platform". Should I install another version of java? Which version of java should I install? Or what should I do to solve this error


text:
Q: maximum stored proc name in firebird I am migrating my db from Interbase to Firebird, and the 1st hiccup we hit comes from our stored proc names.
We have a handful of stored procedures with names greater than 31 characters (which appears to be the max in FB 2.1.3)
Is there a way to increase this limitation? It will be a far easier solution than modifying our software.
Thanks!

A: No there is no way (short of changing the Firebird source code yourself - it is open source, after all).


text:
Q: Can I get a diff of my changes before submitting an edit? When editing a post I usually want to write a concise summary (especially when suggesting an edit).
This would be much easier if I was able to get a diff for my changes. Sometimes editing a post takes quite some time and at the end I don't remember what I changed in the beginning.

A: After editing you can click on the "Edited X ago" link, and see the differences highlighted.
You then have less than 5 minutes to read and summarize your changes, and place them onto the "Edit Summary" line. If you complete your one-liner within the grace period it will appear as a single edit.
Despite the ease of doing that, a checkbox in the Editor would be a great addition.

That would put all the information together on the same screen.

A: You can use a diff checker. E.g diff checker.
Make sure to copy/paste the original post into the diff checker before editing, then you can always get the diff while editing the post.


text:
Q: $GITHUB_OUTPUT - Directory nonexistent (Self hosted runner) I'm trying to use $GITHUB_OUTPUT instead of set-output.
I set up a simple GitHub Action with a docker file based on the official tutorial.
# Container image that runs your code
FROM alpine:latest

# Copies your code file from your action repository to the filesystem path `/` of the container
COPY entrypoint.sh /entrypoint.sh

# Code file to execute when the docker container starts up (`entrypoint.sh`)
ENTRYPOINT ["/entrypoint.sh"]

And the entrypoint.sh is
#!/bin/sh -l

time=$(date)
echo "time=$time" >> $GITHUB_OUTPUT

Executing this in a Self hosted Debian runner results into a
/entrypoint.sh: 4: cannot create : Directory nonexistent

Changing the $GITHUB_OUTPUT with the usual ::set-output works correctly.
Any idea on how to solve this?

A: The deprecation of set-output was mentioned recently (oct. 2022)

If you are using self-hosted runners make sure they are updated to version 2.297.0 or greater.

So check first the version of your runner.

A: Well, yes, the version of the runner is probably one issue.
The other is that the environment variables defined in the shell that creates and runs the container that previously echo "::set-output..." do not have access to GITHUB_OUTPUT unless specifically configured to do so. Moreover, the paths within the container are not the same as that outside, so the path in $GITHUB_OUTPUT won't be available anyway.
The fastest workaround is to add >> $GITHUB_OUTPUT on the docker run command itself, ie. OUTSIDE of the container, and just echo content in there to stdout.


text:
Q: Networkstream.Write() Blocking Problem I'm currently testing a managed c# network library I've written and I've come up against an occasional problem. This problem manifests as a very consistent (always within 30ms) 5000ms block on networkstream.write() for perhaps 1% of all send operations. This is in a test environment, all running locally, using the exact same packet size (2MB) each time. On the client end I continuously write the following to a connected networkstream:
tcpClientNetworkStream.Write(headerBytes, 0, headerBytes.Length);
tcpClientNetworkStream.Write(dataBytes, 0, dataBytes.Length);

and on the server end I use an asynchronous read waiting for data. Once data appears I use a while loop over tcpClientNetworkStream.DataAvailable until all data has been received.
I am aware that networkstream.write() can block if the buffers are full but if this is the problem I can't think of a quicker way of clearing them at the server end (Send and Receive buffer sizes are default at 8192 bytes). The fact the block is so consistent seems very odd. My first thought was possibly some form of Thread.Sleep but doing a full project search shows none. If anyone could help shed some light on this issue that would be greatly appreciated.
Marc
edit to add: A hack which seems to make the problem go away is the following (although there is an associated performance hit due to the BlockCopy):
byte[] bytesToSend = new byte[headerBytes.Length + dataBytes.Length];
Buffer.BlockCopy(headerBytes, 0, bytesToSend, 0, headerBytes.Length);
Buffer.BlockCopy(dataBytes, 0, bytesToSend, headerBytes.Length, dataBytes.Length);
tcpClientNetworkStream.Write(bytesToSend, 0, bytesToSend.Length);

edit to add2: I've also reproduced the problem by using two asynchronous writes with a thread signal between the two. At the moment the only solution I have is the single write operation as in the above edit.
edit to add3: Ok, another possible fix follows. I'm still interested to know why the successive write occasionally 'blocks' in the way it does.
BufferedStream sendStream = new BufferedStream(tcpClientNetworkStream);
sendStream.Write(bytesToSend, 0, bytesToSend.Length);
sendStream.Write(packet.PacketData, 0, packet.PacketData.Length);
sendStream.Flush();

edit to add4: After further extensive testing the solution in 'edit to add3' does not make the problem go away, it just reduces the occurrence to about 0.1% of sends. Much better but far from solved. I will be replacing the asynchronous read with a blocking read next to see if that sorts it, as suggested by PaulF.

A: Ok, no specific answers to this question so I will do my best to provide a little conclusion myself. My best guess is that this problem was originally caused because I was filling the tcp buffer faster than I was clearing it. If the buffer is filled there is some unknown wait time before attempting to add more data. This problem would perhaps be most apparent when sending and receiving data within the same machine. It's important to remember that the default read buffer size in .net is only 8192 bytes, so if writing in much larger chunks, perhaps consider increasing this read buffer size to something larger such as 512000 bytes. However this in itself causes other issues due to the large object heap etc but that is potentially discussion to a different question.


text:
Q: How to send mail to multiple recipients in outlook in vba The below code works fine for one recipient. How do I send the same mail to multiple recipients.
How to send the attachments and how to send mail to multiple recipients in CC.
        All the to recipients are placed in column A of xlSht.
  All the CC recipients are placed in column B of xlSht.

Sub Sendmail()
                         Dim olItem As Outlook.MailItem
                        Dim xlApp As Excel.Application
                        Dim xlBook As Excel.Workbook
                        Dim xlSht As Excel.Worksheet
                        Dim sPath As String
                        sPath = "sss" \\workbook placed locally

                        Set xlApp = CreateObject("Excel.Application")

                        Set xlBook = xlApp.Workbooks.Open(sPath)

                        Set xlSht = xlBook.Sheets("Sheet1")

                    '   // Create e-mail Item
                        Set olItem = Application.CreateItem(olMailItem)

                        With olItem

                        .To = xlSht.Range("A1")

                            .CC = xlSht.Range("B1")

                            .subject = "test"
                            .Display
                           .Send

A: It will be much simpler if you do it from MS-Excel. Open your workbook and paste this code in a module (Untested)
Option Explicit

Sub Sample()
    Dim OutApp As Object, OutMail As Object
    Dim ws As Worksheet
    Dim i As Long, lRow As Long

    Set OutApp = CreateObject("Outlook.Application")

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .To = ws.Range("A" & i).Value
                .Cc = ws.Range("B" & i).Value
                .Subject = "Blah Blah"
                .Body = "Blah Blah"
                .Attachments.Add "C:\Temp\Sample.Txt"

                .Display
            End With
        Next i
    End With
End Sub

And if you still want to do it from MS-Outlook then try something like this (Untested)
Option Explicit

Const xlUp As Long = -4162

Sub Sample()
    Dim oXLApp As Object, oXLWb As Object, oXLWs As Object
    Dim i As Long, lRow As Long
    Dim olItem As Outlook.MailItem

    Set oXLApp = CreateObject("Excel.Application")
    Set oXLWb = oXLApp.Workbooks.Open("C:\MyExcelFile.Xlsx")
    Set oXLWs = oXLWb.Sheets("Sheet1")

    With oXLWs
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            Set olItem = Application.CreateItem(olMailItem)

            With olItem
                .To = oXLWs.Range("A" & i).Value
                .Cc = oXLWs.Range("B" & i).Value
                .Subject = "Blah Blah"
                .Body = "Blah Blah"
                .Attachments.Add "C:\Temp\Sample.Txt"

                .Display
            End With
        Next i
    End With
End Sub

A: Instead of setting CC property, call Recipients.Add (returns Recipient object) and set Recipient.Type property to olCC.


text:
Q: How to get part of an utterance that could be anything If i have an intent like
'How much have I spent on'
that I'd like to match basically 'how much have i spent on ___________________'
where ____ could be any word or phrase.
I've been doing this sort of thing for some intents that do some fuzzy matching to determine what the user is speaking of and it works ok, but is it possible to do this in a reliable way, without requiring that a particularly specific phrase was uttered (which defeats the purpose of NLU to a degree)?
I have been looking for a keyword and assuming their "topic" is the remainder of the phrase, and it works, but seems like it will be prone to problems when the actual user doesn't say more or less what I intended.
I imagine I can reorganize to do this with a follow up intent, like "what category?"  and then treat the entire response as what I was trying to parse out, I was just looking to avoid it if there was some sort of built in support for this concept.
Thanks!

A: I think you are on the right path.
You can use @sys.any entity to capture any word or phrase. And according to your use-case and what the intent is, you can add few variations of the sentences how much have i spent on @sys.any in the utterances.
You can also make use of slot-filling or some other fallback mechanism to validate the user input.


text:
Q: How can we take the result of `MethodInvokingTaskletAdapter` as a reader in the Spring Batch Step? How can we take the result of MethodInvokingTaskletAdapter as a reader in the Spring Batch Step? Reference - https://docs.spring.io/spring-batch/docs/current/reference/html/index-single.html#taskletStep and https://github.com/spring-projects/spring-batch/pull/567
Here is the code that I developed
JobConfiguration.java
@Configuration
public class JobConfiguration {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public CustomService service() {
        return new CustomService();
    }

    @StepScope
    @Bean
    public MethodInvokingTaskletAdapter methodInvokingTasklet() {
        MethodInvokingTaskletAdapter methodInvokingTaskletAdapter = new MethodInvokingTaskletAdapter();
        methodInvokingTaskletAdapter.setTargetObject(service());
        methodInvokingTaskletAdapter.setTargetMethod("getEmployees");
        return methodInvokingTaskletAdapter;
    }

    @Bean
    public Job methodInvokingJob() {
        return this.jobBuilderFactory.get("methodInvokingJob")
                .start(methodInvokingStep())
                .build();
    }

    @Bean
    public Step methodInvokingStep() {
        // Looking to configure the Chunk based Step here, dont know how to do using MethodInvokingTaskletAdapter
        return this.stepBuilderFactory.get("methodInvokingStep")
                .tasklet(methodInvokingTasklet())
                .build();
    }
}

CustomService.java
public class CustomService {
    public void serviceMethod(String message) {
        System.out.println(message);
    }

    public void invokeMethod() {
        System.out.println("=============== Your method has executed !");
    }

    public List<Employee> getEmployees(){
        // In real world, it will be an GET API call to XYZ system
        List<Employee> employees = new ArrayList<>();
        employees.add(Employee.builder().firstName("Ravi").lastName("Shankar").email("ravi.shankar@gmail.com").age(30).build());
        employees.add(Employee.builder().firstName("Parag").lastName("Rane").email("parag.rane@gmail.com").age(11).build());
        employees.add(Employee.builder().firstName("Priya").lastName("Pande").email("priya.pande@gmail.com").age(40).build());
        employees.add(Employee.builder().firstName("Kiran").lastName("khot").email("kiran.khot@gmail.com").age(50).build());
        return employees;
    }
}

Employee.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Employee {
    private String firstName;
    private String lastName;
    private String email;
    private int age;
}

MethodInvokingTaskletApplication.java
@EnableBatchProcessing
@SpringBootApplication
public class MethodInvokingTaskletApplication {

    public static void main(String[] args) {
        SpringApplication.run(MethodInvokingTaskletApplication.class, args);
    }
}

A: To answer your question, you can't. The MethodInvokingTaskletAdapter is meant to adapt a POJO to a Tasklet. We have an ItemReaderAdapter that you can use to adapt a POJO to an ItemReader. You can read about it in the documentation here: https://docs.spring.io/spring-batch/docs/current/api/org/springframework/batch/item/adapter/ItemReaderAdapter.html
Now you'll have an issue with your service as configured in that each call to the delegating POJO is considered an item. That means that your item as configured will be a List<Employee> instead of just an Employee. Given your configuration states it's not the real service, I'll assume that your real service should return an Employee per call and null once the results are exhausted.
To update your configuration (with your service as it is configured in your question) in your sample:
...
    @StepScope
    @Bean
    public ItemReaderAdapter itemReader() {
        ItemReaderAdapter reader = new ItemReaderAdapter();
        reader.setTargetObject(service());
        reader.setTargetMethod("getEmployees");
        return reader;
    }

    @Bean
    public Job methodInvokingJob() {
        return this.jobBuilderFactory.get("methodInvokingJob")
                .start(methodInvokingStep())
                .build();
    }

    @Bean
    public Step methodInvokingStep() {
        return this.stepBuilderFactory.get("methodInvokingStep")
                .<List<Employee>, List<Employee>>chunk(methodInvokingTasklet())
                .reader(itemReader())
                // You'll need to define a writer...
                .writer(itemWriter())
                .build();
    }
    ...


text:
Q: How do I automate dependency installation after pulling code from repository? My collegue and I develop a small Python application. We use Vagrant to set up development environments.
Suppose my collegue introduces a new feature into the application. Feature's implementation requires a new python dependency (3rd party package) and the dependency itself needs some system libraries. If I do not read through all pulled commits carefully I can miss, that some systems libraries have to be installed prior running the project.
Of course we update Vagrantfile to install such non-python dependencies during provisioning, so if someone clones project's repository and issues vagrant up he will get a fully working development environment, but what shoud I do to automate updates in my existing environment?
How should we indicate, that a new dependency (python or non-python) was added and we need to install it by firing a specific command?
UPD I can try and run the application and if I encounter any errors it is a sign to reprovision my vagrant box, but it seems tedious to me to test a feature by hands and run provisioning scripts later

A: I ran into this with Ruby as well. We used Bundler, which is a dependency management system for Ruby. If I pulled in new code, ran it and got funky exceptions saying that a certain dependency was missing, I just knew it was time for a bundle install from the command line. The solution to your problem is the same. If you run the code and get errors saying a dependency is missing, your default response to that exception should be to vagrant up on the command line, and try again.
Barring that, sending an email to your teammates with instructions about the new or updated dependency is a good way to go, especially if a vagrant up is insufficient to resolve the missing or incorrect dependency.


text:
Q: How to create a polars data frame from a dictionary which has unequal length values? I have a dictionary as:
ex_dict = {'A': ['false',
  'true',
  'false',
  'false',
  'false',
  'true',
  'true',
  'false',
  'false'],
 'B': ['false',
  'false',
  'true',
  'false',
  'false',
  'false'],
  'C': ['false',
  'true',
  'true',
  'false',
  'false',
  'false',
  'false',
  'false',
  'true']}

I'm creating a dataframe as:
pl.DataFrame(ex_dict)

on executing it gives an error as:
ShapeError: Could not create a new DataFrame from Series. The Series have different lengths.Got [shape: (9,)

How to create a polars dataframe in these scenarios ?

A: You can place each Series into its own DataFrame, and use a concat with how="horizontal".  This will automatically extend shorter Series with null values.
pl.concat(
    items=[pl.DataFrame({_name: _values})
           for _name, _values in ex_dict.items()],
    how="horizontal",
)

shape: (9, 3)
┌───────┬───────┬───────┐
│ A     ┆ B     ┆ C     │
│ ---   ┆ ---   ┆ ---   │
│ str   ┆ str   ┆ str   │
╞═══════╪═══════╪═══════╡
│ false ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ true  ┆ false ┆ true  │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ true  ┆ true  │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ true  ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ true  ┆ null  ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ null  ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ null  ┆ true  │
└───────┴───────┴───────┘


text:
Q: Making a List Item read-only I'm a newbie so please be gentle. I have created a List from which I can add Items linked to documents in my Library. So far so good. I am the only person that can upload to new docs to the Library and therefore the only person that can update the List - I am the only one with Edit perms.
When a user (who should only have read access) clicks on an item in the List they get a check-out doc option. How do I get the List to work so that when a user clicks on an item it opens the document (they are all in PDF form) straightaway in another tab without the checkout/checkin functions?
Hope all of this makes sense. Many thanks.

A: In the Document Library settings, you can go to Versioning and disable the Check In/Out setting. This is typically used when one needs to place an exclusive lock for editing purposes, but as these are PDFs, editing is unlikely.


text:
Q: How to make background change colour in a flashing effect I am trying to make the background flash when music plays in my app but it isn't working as expected.
The music plays when a button is pressed. The background should be yellow when the music is off but flash quickly between yellow and purple when the music is playing.
At the moment it is yellow when off, changes to some dull grey when the music is playing and does not return to yellow when the music is off.
public class InstaRave extends Activity {

private static final String TAG = "InstaRave";
private static int isPlaying = 0; // 0 is not playing 1 is playing
private MediaPlayer mp;
public static int mPurple = color.mPurple;
public static int mYellow = color.mYellow;
public static int currentBackground = mYellow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_insta_rave);

    final Button play_button = (Button)this.findViewById(R.id.raveButton);
    final RelativeLayout mRelativeLayout = (RelativeLayout) this.findViewById(R.id.topLevelLayout);

    mp = MediaPlayer.create(this, R.raw.rave_mk);

    Log.v(TAG, "Initializing sounds...");

    play_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            switch (isPlaying){
                case 0:
                    changeBackground(mRelativeLayout);
                    startMusic();
                    isPlaying = 1;
                    rave();
                    break;
                case 1:
                    changeBackground(mRelativeLayout);
                    stopMusic();
                    isPlaying = 0;
                    rave();
                    break;
                default:
                    Log.e(TAG, "Ooops something went wrong");
            }
        }

        private void stopMusic(){
            Log.v(TAG, "Stopping sound...");
            mp.stop();
            //isPlaying = 0;
            mp.prepareAsync();
        }

        private void startMusic(){
            Log.v(TAG, "Playing sound...");
            mp.start();
            //isPlaying = 1;
        }

        private void rave(){
            Log.v(TAG, String.valueOf(isPlaying));
            if (isPlaying == 1){
                Log.v(TAG, "Raving....");
                new Rave().execute();
            } else {
                Log.v(TAG, "End the rave the po po is here...");
            }
        }

    });
}

protected void onPause(){
    super.onPause();
    mp.release();
    mp = null;
}

private void changeBackground(RelativeLayout mRelativeLayout){
    if (currentBackground == mYellow){
        currentBackground = mPurple;
        mRelativeLayout.setBackgroundColor(currentBackground);
        Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
    }
    currentBackground = mYellow;
    mRelativeLayout.setBackgroundColor(currentBackground);
    Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}

private class Rave extends AsyncTask<Void, Void, Void> {
    final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.topLevelLayout);

    @Override
    protected Void doInBackground(Void... params) {
        while (isPlaying ==1){
            try {
                Thread.sleep(75);
                publishProgress();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    protected void onProgressUpdate(Void... progress){
        changeBackground(mRelativeLayout);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.insta_rave, menu);
    return true;
}

}

A: Change your changeBackground() method to this:
private void changeBackground(RelativeLayout mRelativeLayout){
  if (currentBackground == mYellow){
      currentBackground = mPurple;
      mRelativeLayout.setBackgroundColor(currentBackground);
      Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
  }
  else
  {
     currentBackground = mYellow;
     mRelativeLayout.setBackgroundColor(currentBackground);
     Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
  }
}


text:
Q: Permit to a discord bot to reach messages data of a dirict message discussion I'm using discord.js and I would like to analyze messages of a DM dicussion using a bot.
I have a simple question, is there a way to reach data of a DM discussion with someone using a bot(giving at the bot the permission to reach the messages).
I'm not sure if this is possible or not, I was thinking at something like a getMessageById or similar, but it's obvious that this would be a massive privacy  problem of the message.
Let me know if is there a way, but I'm quite sure that there isn't one.
Thank you, have a great day.

A: Bots can only check the dm between themselves and the user. No dms between two users ofc.
Self bots would be able to but discord patched em I believe.


text:
Q: having trouble in installing composer on for wamp From last 3 days i am trying to install composer on my local system WAMP (windows 7). When i install composer it through an error :

The "https://getcomposer.org/versions" file could not be downloaded:
  failed to open stream: An attempt was made to access a socket in a way
  forbidden by its access permissions.

Any help would be appreciated.


text:
Q: Android ListView and EditView on AlertDialog crash I test my application on debug and crash on this line:
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);

with this error:
System services not available to Activities before onCreate()

I solved this error whit this code (change this with context):
    listAdapter = new ArrayAdapter(promptsView.getContext(), R.layout.cd_edittext_for_listview, planetList);
And change on XML file "EditView" with "EditText"!*

I have this layout for the items "editText_for_listview.xml":
<EditView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rowEditView"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="10dp"
  android:textSize="16sp">
</EditView>

And my main layout "items_listview.xml"
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="10dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

  <ListView
      android:layout_marginTop="10dp"
      android:layout_marginBottom="10dp"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/mylistview"
      android:layout_gravity="center" />

</LinearLayout>

The code is this:
public void _ShowItems(String sTitle,android.content.Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(sTitle);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    final View promptsView = inflater.inflate(R.layout.items_listview, null);

    ListView mainListView ;
    ArrayAdapter<String> listAdapter ;
    mainListView = (ListView) promptsView.findViewById( R.id.editText_for_listview );

    String[] planets = new String[] { "Test1", "Test2", "Test3" };
    ArrayList<String> planetList = new ArrayList<String>();
    planetList.addAll( Arrays.asList(planets) );

    listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);

    // Set the ArrayAdapter as the ListView's adapter.
    mainListView.setAdapter( listAdapter );
    builder.setView(promptsView)
            .setPositiveButton("One", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            })
            .setNegativeButton("Two", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            });

    builder.show();
}

Can you help me?
Where I wrong?
Thanks

A: Obviously you are trying to use the Activity Context prior to the Activity's onCreate() method being called. Try moving your call to _ShowItems() to onResume() method.

A: Could you show up more code of your activity. You could just be calling the method in a spot where the context isn't initialized but something else could be going on that will be revealed once we have a better look at the activity.
I would have made this a comment but I don't have the reputation to do so.


text:
Q: Tooltip doesn't set inside a modal I'm trying to set a tooltip inside a modal, but it only show the title.

I've already tried set tooltip when the modal is shown but nothing happens.
$(ele).on('shown.bs.modal', function () {
   $('[data-toggle="tooltip"]').tooltip();
});

The button is like that:
<button class="btn btn-primary btn-select2" data-toggle="tooltip" type="button" data-placement="top" title="Selecionar todos"></button>

So far, even the title shown up.
So, I have a function that every time that modal is open, it does a foreach to find these buttons (to do another action) but I inserted again the title, data-original-title and tooltip, like this:
$('modal').find('.btn-select2').each(function() {
    $(this).attr('title', 'Selecionar Todos');
    $(this).attr('data-original-title', 'Selecionar Todos');
    $(this).data('placement', 'top');
    $(this).tooltip();
});

After that, the title starts to show like the image, but no success with the tooltip. Any solution?
EDIT:
Here's the HTML of the button that is inserted inside the modal

    Cargos

        <select name="charges[]" class="form-control select2" multiple>
            @foreach($charges as $charge)
            <option value="{{$charge->id}}">{{$charge->name}}</option>
            @endforeach
        </select>

            <button class="btn btn-primary btn-select2" data-tooltip="tooltip" data-toggle="tooltip" type="button" data-placement="top" title="Selecionar todos"></button>

In the end of the document, I put:
$(function () {
    $('[data-toggle="tooltip"]').tooltip();
    $('.modal').on('shown.bs.modal', function () {
        $('[data-toggle="tooltip"]').tooltip();
    });
    $('.btn-select2').tooltip();
});

And have some modals, that use a function to open, and it's in these modals that the title shown up but the tooltip doesn't. In the other modals that just use data-toggle to open, even the title is shown. Here is the code of the function:
const modalUpdate = function(obj, ele, hasSub = false) {
    $(ele).find('.btn-select2').each(function() {
        var button = this;
        var changeHeight = function () {
            var newHeight = $(button).parent().parent()[0].children[1].children[0].children[0].clientHeight;
            button.style = 'height: ' + (newHeight + 2) + 'px!important';
        }
        setTimeout(function() {
            changeHeight();
        }, 200);
        $(this).attr('title', 'Selecionar Todos');
        $(this).attr('data-original-title', 'Selecionar Todos');
        $(this).data('placement', 'top');
        $(this).tooltip();
    });
}


text:
Q: Python: pickle.load __init__ error I have trained a HMM model to add punctuation into Arabic text and I want to save it to not repeating the training phase every time I enter a text to the model for tagging it .. I use pickle for these task as I see in tutorials. I do exactly like them but it fail and give me these error!.
Traceback (most recent call last):
  File "C:\Python27\file_pun_tag.py", line 205, in <module>
    hmm_tagger("test_file.txt")
  File "C:\Python27\file_pun_tag.py", line 179, in hmm_tagger
    hmm = pickle.load(saved_model)
  File "C:\Python27\lib\pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "C:\Python27\lib\pickle.py", line 858, in load
    dispatch[key](self)
  File "C:\Python27\lib\pickle.py", line 1133, in load_reduce
    value = func(*args)
TypeError: __init__() takes at least 3 arguments (2 given)

I tried several solutions but none of them working with me ...
Here is the code where I save my model. It is working correctly for saving the model and creating the "hmm.pickle":
file = codecs.open("train_sents_hmm.txt", "r", "utf_8")
train_sents = file.readlines()
labelled_sequences, tag_set, symbols = load_pun(train_sents)
trainer = nltk.HiddenMarkovModelTrainer (tag_set, symbols)
hmm = trainer.train_supervised (labelled_sequences, estimator=lambda fd, bins: LidstoneProbDist(fd, 0.1, bins))

# save object
save_model = open("hmm.pickle", "wb")
pickle.dump(hmm, save_model, -1)
save_model.close()

And here is the code when i'm trying to load the model after saving it, and here where it gives me the error:
saved_model = open("hmm.pickle", "rb")
hmm = pickle.load(saved_model)
saved_model.close()