text:
Q: Office Analysis Prompts Value Macro I have a vba code to open prompts window in excel:
Application.Run("SAPExecuteCommand", "ShowPrompts")
But my problem is I dont know how to put value in Prompts window through Macro. Can anyone help about that? Any code sample?
For instance in this picture I want to put 1000 in 0BUCHUNG field. I would like to do this through Macro code and click ok. I cant record a Macro while doing these steps I dont know why, that is why I am asking maybe there is kind of code to perform it in Macro. Prompts Window


text:
Q: Switch to specific tab in Vim like in Firefox? How do I make Vim switch to a certain tab when I hit Alt+# ?  For example, to get to the third tab, I'd hit Alt+3 (like the behavior in Firefox).
Edit: also, how can I make Control + tab == gt, Control + shift + tab == gT

A: :nmap <M-1> :tabnext 1<CR>
:nmap <M-2> :tabnext 2<CR>
etc.

See :h :tabnext.  Note that by default you can also do Ngt in normal mode where N is the number of the tab you want (starting with 1).

A: This works for me (copied and pasted from my rc):
" Tab Control (others)
 map <A-1> 1gt
 map <A-2> 2gt
 map <A-3> 3gt
 map <A-4> 4gt
 map <A-5> 5gt
 map <A-6> 6gt
 map <A-7> 7gt
 map <A-8> 8gt
 map <A-9> 9gt

Also further goodness:
map <C-Right> <ESC>:tabnext<CR>
map <C-Left> <ESC>:tabprev<CR>
map <C-t> <ESC>:tabnew<CR>

You may want to change it to nmap like the example above to restrict the usage a little better I've been a bit lazy in that respect.
Missed your edit next tab with Ctl-t would be:
map <C-t> :tabnext<CR>

I don't think the tabprevious mapping is possible in vim due to the way it handles uppercase  characters see:
http://www.nabble.com/Maping-Ctrl-Shift-s-problems-td22918941.html
To save some time I spent hunting around when I wanted this

A: Getting this to work in urxvt proved difficult. Eventually I settled on using the folowing bindings:
:nnoremap <Esc>1 gt1
:nnoremap <Esc>2 gt2
:nnoremap <Esc>3 gt3
:nnoremap <Esc>4 gt4
:nnoremap <Esc>5 gt5
:nnoremap <Esc>6 gt6
:nnoremap <Esc>7 gt7
:nnoremap <Esc>8 gt8
:nnoremap <Esc>9 gt9
:nnoremap <Esc>0 gt0

The problem was that Alt number combinations get bound to escape prefixed numbers by default in rxvt. Originally I managed by having the following in my ~/.vimrc file:
:nnoremap <M-1> gt1
:nnoremap <M-2> gt2
...

This was made to work by using the following to '~/.Xdefaults':
URxvt*meta8: true

This forces rxvt to use the 8th character bit when Alt is pressed, which is what Vim uses to detect the Alt state. Setting this in your .Xdefaults file enables the 8th bit to be set. However, this causes problems in other programs, such as irssi running over screen, hence my suggested solution.

A: On Mac, you may want use the cmd + number to switch tabs. The following works well.
map <D-1> 1gt
map <D-2> 2gt
map <D-3> 3gt
etc...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Switching SharePoint traffic from one server to another For deployments, I want to be able to quickly move traffic from one front end to another with out adding additional hardware.  How can this be done?

A: I would think with a load balancer. In normal state you can let the load balancer decide which front end to use. When you want to deploy to frontend 1, you can derive all traffic to frontend 2. Then when frontend 1 is deployed you can do the same for frontend 2.

A: can't do it 'quickly' without a load balancer. Alternatively, and slower, would be to update the DNS for the site to point to the other web front end.
HTH


text:
Q: Converting Linux machine from XenServer to Hyper-V VM I have a XenServer on a physical machine and I want to put it into my Hyper-V environment as a VM. Is this Possible ?
Thanks

A: This is what the ovf/ova format is for (ova is just an ovf image inside a tar file).
You can export your VM in an ova format following these instructions, and you can import them into Microsoft HyperV by using Kensho. Kensho has been incorporated into Xenserver 5.6 and later, and its functionality (not its name) has been rolled into XenCenter and XenConvert. So, in line of principle, if you run a reasonably recent version of Xenserver, you should be able to do it all from within Xen. If you need help, read this Citrix forum thread, and possibly more posts within the same forum.
Importing ova into HyperV requires a dedicated tool because Microsoft does not follow widely agreed-upon open-source standards (God forbid!). But some generous soul (once again Citrix) provided a tool to allow importing  ova into HyperV.


text:
Q: JavaScript associate arrays comparing I suppose that I have three arrays:
dict['tag'] = 'INPUT';
dict['type'] = 'checkbox';
dict['name'] = 'remember'

dict2['tag'] = 'INPUT2';
dict2['type'] = 'checkbox';
dict2['name'] = 'remember';

dict3['type'] = 'checkboxEdit';
dict3['name'] = 'remember'
dict3['tag'] = 'INPUT3';

Now what I want to achieve is that I want know how many elements of arrays are equal even when arrays are not sorted, so for instance
function(dict, dict2) return 2 //cause input values are not the same
function(dict, dict3) return 1 //cause name values are the same
function(dict2, dict3) return 1 //cause name values are the same

What is the most effective way to achieve this ? Also data structure can be changed so if there is something better, let me know.

A: It's pretty simple realy..

var dict = {}, dict2 = {}, dict3 = {};

dict['tag'] = 'INPUT';
dict['type'] = 'checkbox';
dict['name'] = 'remember'

dict2['tag'] = 'INPUT2';
dict2['type'] = 'checkbox';
dict2['name'] = 'remember';

dict3['type'] = 'checkboxEdit';
dict3['name'] = 'remember'
dict3['tag'] = 'INPUT3';

function compare(d1, d2) {
  var count = 0;
  Object.keys(d1).forEach(function (k) {
      if(d1[k] === d2[k]) count++;
  });
  return count;
}

alert(compare(dict, dict2));
alert(compare(dict, dict3));
alert(compare(dict2, dict3));


text:
Q: Is there any existing Library for this kind of image viewer? I can't explain it properly when searching in google, so I hope someone here is able to point it out for me. If there are no existing libraries, then, I'll have to manually create it and you might be able to give me hints of how I should implement it. Thank you very much!

A: You can check following libraries to get your desired result.
1> iCarousal
2> YRCoverflow
3> Scaling Carousal
4> LNICoverflowLayout


text:
Q: Преобразование объект в массив JavaScript Имеется такой объект:
var json_data = {"city":"Shanghai","country": "China", "car": "China"}

Как в JavaScript преобразовать его в вид массива и каждый key с его value был отдельный объект:
[
  {"city":"Shanghai"},
  {"country": "China"},
  {"car": "China"}
]

A: Используйте цикл for..in, в теле которого при каждой итерации в массив будет записан новый объект, состоящий из ключа / значения нужного объекта.
var json_data = {"city":"Shanghai","country": "China", "car": "China"}
var arr = [];
for (let key in json_data) {
    arr.push({[key]: json_data[key]})
}


text:
Q: Spring cloud dataflow - Composite Task with external configuration I have a composite task with two cloud task ( AAA && BBB ).
I want to pass the properties to AAA and BBB task from a directory.
For example, the usage of "--spring.config.location=directory/" when launching the Spring boot application.
As per the documentation, i understand that we can pass properties using app.CompositeTaskName.taskname.prop1=val1.
But, i want to load a bunch of configuration at launch.
So, is there a way to launch the tasks with "spring.config.location" argument ?

A: I found the solution. I passed "--spring.config.location" in the task definition of my composite task.
task create myctr --definition "AAA --spring.config.location=/data/prop/ '*'->BBB"

I launched the composite task "myctr" and it referred the property files from the "/data/prop/" directory.
Documentation reference :
http://docs.spring.io/spring-cloud-dataflow/docs/1.7.4.RELEASE/reference/htmlsingle/#spring-cloud-dataflow-composed-tasks
--> Task Application Parameters


text:
Q: Returning number of cells in a table produces NSInternalInconsistenceyException Trying to add a section with 6 cells in my table. I just have some basic code and it is failing to compile giving me "'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'". I believe it has something to do with not setting a datasource, but I am not sure. Here is the code:
- (void)viewDidLoad
{
    [super viewDidLoad];
    germanMakes = @[@"Mercedes-Benz", @"BMW", @"Porsche",
                    @"Opel", @"Volkswagen", @"Audi"];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return germanMakes.count;
}

A: You must impement the considered method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = germanMakes[indexPath.row];

    return cell;
}

A: You have not implemented the datasource method which is "cellForRowAtIndexPath" method, make sure you also connect the datasource of table view to your class in Interface builder


text:
Q: org.apache.poi.poifs.filesystem.NotOLE2FileException I am creating an UI where I ask the user to upload an existing excel file and I am getting this error. I have done some searching, and tried to use a POIFileSystem object before passing in the FileInputStream but that didn't. I am getting this error of the line that creates the workbook.
This my code:
public static Cell readExcelFile(byte[] byteFile){
    if (file == null){
        System.out.println("file is empty");
    } else {
        InputStream input = new ByteArrayInputStream(byteFile);
        POIFileSytem fsPOI = new POIFileSytem(input);
        HSSFWorkbook wb = new HSSFWorkbook(fsPOI);
      //continues to read the file
}
}

A: I found an answer! So I as you see from the code above I passed my file as a byte array. Prior to that in my POST request I upload the file as a string and  decode it from base 64 and into an byte array, that were the error occured. It wasn't decode correctly. I printed out what the String version of the file from the  POST endpoint and that consist of "data:application/vmd.ms-excel;base64,OMBR4K(this the file data encoded in base 64 but Im not going to type all of it). Basically it wasn't decoding correctly because of everything before the comma was a regular text header.  I spilt the string and saved everything after the comma in another string, and converted that into a byte array and decoded. Then my file was acceptable and I was able the create the workbook, and I also had to use .getSheetAt(int) instead of .getSheet("string")


text:
Q: Refreshing nested Iframe in the Selenium script I am working on an application which has nested Iframes in the UI. Some of the Iframes refresh during test execution. Is there any way we can simulate refreshing Iframe using Selenium?  I have tried using Javascript and WebDriverWait but it didn't work.
I have used following methods:
public static void waitForIframeToLoad(String frameName){
    WebDriverWait wait = new WebDriverWait(driver,60);
 wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameName));
}

public static void refreshIFrameUsingJavaScript(String iFrameName)
{
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript(String.format("document.getElementById('{0}').src = " +
  "document.getElementById('{0}').src", iFrameName));
 }

However both these methods are not working. I am able to switch between frames using driver.switchTo().frame("main").switchTo().frame("framename")
The frame 'main' is the parent frame and it holds multiple child frames. The child frames refresh after user clicks on some button and I need to verify some text in the child frame after it refreshes.
However after the child frame refreshes, I am unable to access any elements in the script. Has anyone worked on the similar scenario? what is the best possible workaround for this?

A: When you refreshed, your webelement objects become "stale" and are no longer the same objects. You need to (re) instantiate your webelement object(s). You may need to even switch back to the Parent frame first, then go to the child frame, and finally instantiate your webelement objects.


text:
Q: Making sure that objects in nibs are initialized before applicationDidFinishLaunching and thanks for taking a look at my problem.
i have two view controllers in my app and each has its own nib file. an instance of controller1 is stored in MainWindow.xib and an instance of controller 2 is in Controller1.xib.
is there a way to make sure that controller 2 is initialized before the app delegate is sent applicationDiDFinishLaunching?
the actual setup is much more complicated with many other view controllers, so i really don't want to put everything into MainWindow.xib. plus doing so will reduce reusability.
thanks again!

A:
is there a way to make sure that controller 2 is initialized before the app delegate is sent applicationDiDFinishLaunching?

No. Well, maybe yes, but it's not how view controllers are supposed to work. The view controller is there to defer the loading of the nib, which is a rather expensive operation,  until the view is really, really necessary. So, if you need controller2 right when applicationDidFinishLaunching is called, you shouldn't put it inside the nib which is controlled by another view controller.
If I were you, I would stop instantiating the view controllers in the nib file at all, and just create them inside applicationDidFinishLaunching:, as in
-(void)applicationDidFinishLaunching:(UIApplication *)application
{
     ....
     self.controller2=[[Controller2 alloc] init... ];
     ....
}

A: I believe applicationDidFinishLaunching is the absolute entry point in which you have control of the code.  That's conceivably the earliest place to load anything.


text:
Q: How to prioritize variables in GLM in R? I am relatively new to R and GLMs.  I have a simple GLM y ~ a+b. a is the dominant variable and I would like the coefficients to basically give more weight to a and then use b to explain the remainder.  I have created a simplified example to illustrate a problem I am running into.  The coefficient with variable "b" is not aligning with expectations due to mix differences in variable "a" within the data. I'm probably doing something wrong.  In my actual data, tweedie is the right model, so I used it for this made-up data, however it probably isn't the right fit here.  Hopefully this still illustrates what I am trying to do. I've looked at R help for offsets and weights and I still don't understand how to use them correctly.  I am copying the form of a tweedie GLM I saw used in a presentation. So, what do I need to do to get this GLM to accurately recognize that if b = 3, the coefficient should be 1.5 and if b = 2, the coefficient should be 1.0?
##  example ##############################

a <- 1:20
a[1:10] <- a[1:10]* 100
a[11:20] <- a[1:10] * 100
# true coef
a_coef <- 0.2

b <- 1:20
b[1:10] <- 3 # true coef = 1.5
b[11:20] <- 2 # true coef = 1.0

# true formula for y
y <- a_coef*a*ifelse(b==3,1.5,1)

count <- 1:20
count[1:20] <- 1

data <-data.frame(cbind(y,a,b,count))
data$b <- factor(data$b)

set.seed(1)
x <- tweedie.profile(y ~ 1, offset=log(count),
                     do.plot=TRUE, do.smooth=FALSE, method="series",
                     data=data)

tweedie.p <- x$xi.max

# glm to predict y
glm_example <- glm(y ~ a+b,
            family=tweedie(var.power=tweedie.p, link.power=0),
            data=data, offset=log(count),
            weights=count^(tweedie.p - 1))

summary(glm_example)

data$glm <- predict(glm_example,newdata=data,type="response")

glm_example_names <- names(glm_example$coefficients)
glm_example_coefs <- cbind(glm_example_names,exp(glm_example$coefficients),
                           glm_example$coefficients)
glm_example_coefs

# Model: y=2647.56*1.0000227^a*ifelse( b = 3, 0.06,1)
# desired model: y=0.2*a*ifelse(b=3,1.5,1)

A: I figured out the problem with the code.  If I change the offset from offset(count) to offset(a) it works perfectly showing intercept = 0.2 and the coefficient for b = 3 is 1.5.


text:
Q: TotalUsers задваивает значения Делаю запросы с GA4 Query Explorer
Когда я запрашиваб два измерения (dimension) одновременно (appVersion and firstUserCampaignId), то суммарное значение поля totalUsers задваивается (по отношению к Google Analytics)
Когда я запрашиваю только одно из этих измерений, то приходят корректные данные и сумма всех totalUsers совпадает с аналитикой. Причём до 15го января данные были корректны.
Это некий баг в GA4?
{"dimensions":[{"name":"appVersion"},{"name":"date"},{"name":"firstUserCampaignId"},{"name":"platform"},{"name":"streamId"}],"metrics":[{"name":"newUsers"},{"name":"totalUsers"}],"dateRanges":[{"startDate":"2023-01-27","endDate":"2023-01-27"}]}


text:
Q: Is there any better way to check if the same data is present in a table in .Net core 3.1? I'm pulling data from a third party api. The api runs multiple times in a day. So, if the same data is present in the table it should ignore that record, else if there are any changes it should update that record or insert a new record if anything new shows up in the json received.
I'm using the below code for inserting any new data.
 var input = JsonConvert.DeserializeObject<List<DeserializeLookup>>(resultJson).ToList();

 var entryset = input.Select(y => new Lookup
 {
     lookupType = "JOBCODE",
     code = y.Code,
     description = y.Description,
     isNew = true,
     lastUpdatedDate = DateTime.UtcNow
 }).ToList();
 await _context.Lookup.AddRangeAsync(entryset);
 await _context.SaveChangesAsync();

But, after the first run, when the api runs again it's again inserting the same data in the table. As a result, duplicate entries are getting into table. To handle the same, I used a foreach loop as below before inserting data to the table.
foreach (var item in input)
{
    if (!_context.Lookup.Any(r =>
    r.code== item.Code))
    {
       //above insert code
    }
}

But, the same doesn't work as expected. Also, the api takes a lot of time to run when I put a foreach loop. Is there a solution to this in .net core 3.1

A:     List<DeserializeLookup> newList=new();
foreach (var item in input)
{
    if (!_context.Lookup.Any(r =>
    r.code== item.Code))
    {
     newList.add(item);
       //above insert code
    }
}
await _context.Lookup.AddRangeAsync(newList);
 await _context.SaveChangesAsync();

It will be better if you try this way

A: I'm on my phone so forgive me for not being able to format the code in my response. The solution to your problem is something I actually just encountered myself while syncing data from an azure function and third party app and into a sql database.
Depending on your table schema, you would need one column with a unique identifier. Make this column a primary key (first step to preventing duplicates). Here's a resource for that: https://www.w3schools.com/sql/sql_primarykey.ASP
The next step you want to take care of is your stored procedure. You'll need to perform what's commonly referred to as an UPSERT. To do this you'll need to merge a table with the incoming data...on a specified column (whichever is your primary key).
That would look something like this:
MERGE
   Table_1 AS T1
USING
   Incoming_Data AS source
ON
   T1.column1 = source.column1
   /// you can use an AND / OR operator in here for matching on additional values or combinations
WHEN MATCHED THEN
   UPDATE SET T1.column2= source.column2
//// etc for more columns
WHEN NOT MATCHED THEN
   INSERT (column1, column2, column3) VALUES (source.column1, source.column2, source.column3);

A: First of all, you should decouple the format in which you get your data from your actual data handling. In your case: get rid of the JSon before you actually interpret the data.
Alas, I haven't got a clue what your data represents, so Let's assume your data is a sequence of Customer Orders. When you get new data, you want to Add all new orders, and you want to update changed orders.
So somewhere you have a method with input your json data, and as output a sequence of Orders:
IEnumerable<Order> InterpretJsonData(string jsonData)
{
    ...
}

You know Json better than I do, besides this conversion is a bit beside your question.
You wrote:

So, if the same data is present in the table it should ignore that record, else if there are any changes it should update that record or insert a new record

You need an Equality Comparer
To detect whether there are Added or Changed Customer Orders, you need something to detect whether Order A equals Order B. There must be at least one unique field by which you can identify an Order, even if all other values are of the Order are changed.
This unique value is usually called the primary key, or the Id. I assume your Orders have an Id.
So if your new Order data contains an Id that was not available before, then you are certain that the Order was Added.
If your new Order data has an Id that was already in previously processed Orders, then you have to check the other values to detect whether it was changed.
For this you need Equality comparers: one that says that two Orders are equal if they have the same Id, and one that says checks all values for equality.
A standard pattern is to derive your comparer from class EqualityComparer<Order>
class OrderComparer : EqualityComparer<Order>
{
    public static IEqualityComparer<Order> ByValue = new OrderComparer();

     ... // TODO implement
}

Fist I'll show you how to use this to detect additions and changes, then I'll show you how to implement it.
Somewhere you have access to the already processed Orders:
IEnumerable<Order> GetProcessedOrders() {...}

var jsondata = FetchNewJsonOrderData();

// convert the jsonData into a sequence of Orders
IEnumerable<Order> orders = this.InterpretJsonData(jsondata);

To detect which Orders are added or changed, you could make a Dictonary of the already Processed orders and check the orders one-by-one if they are changed:
IEqualityComparer<Order> comparer = OrderComparer.ByValue;
Dictionary<int, Order> processedOrders = this.GetProcessedOrders()
                                             .ToDictionary(order => order.Id);

foreach (Order order in Orders)
{
    if(processedOrders.TryGetValue(order.Id, out Order originalOrder)
    {
        // order already existed. Is it changed?
        if(!comparer.Equals(order, originalOrder))
        {
             // unequal!
             this.ProcessChangedOrder(order);
             // remember the changed values of this Order
             processedOrder[order.Id] = Order;
        }
        // else: no changes, nothing to do
     }
     else
     {
         // Added!
         this.ProcessAddedOrder(order);
         processedOrder.Add(order.Id, order);
     }
 }

Immediately after Processing the changed / added order, I remember the new value, because the same Order might be changed again.
If you want this in a LINQ fashion, you have to GroupJoin the Orders with the ProcessedOrders, to get "Orders with their zero or more Previously processed Orders" (there will probably be zero or one Previously processed order).
var ordersWithTPreviouslyProcessedOrder = orders.GroupJoin(this.GetProcessedOrders(),

   order => order.Id,                     // from every Order take the Id
   processedOrder => processedOrder.Id,   // from every previously processed Order take the Id

   // parameter resultSelector: from every Order, with its zero or more previously
   // processed Orders make one new:
   (order, previouslyProcessedOrders) => new
   {
       Order = order,
       ProcessedOrder = previouslyProcessedOrders.FirstOrDefault(),
   })
   .ToList();

I use GroupJoin instead of Join, because this way I also get the "Orders that have no previously processed orders" (= new orders). If you would use a simple Join, you would not get them.
I do a ToList, so that in the next statements the group join is not done twice:
var addedOrders = ordersWithTPreviouslyProcessedOrder
    .Where(orderCombi => orderCombi.ProcessedOrder == null);
var changedOrders = ordersWithTPreviouslyProcessedOrder
    .Where(orderCombi => !comparer.Equals(orderCombi.Order, orderCombi.PreviousOrder);

Implementation of "Compare by Value"
// equal if all values equal
protected override bool Equals(bool x, bool y)
{
    if (x == null) return y == null;  // true if both null, false if x null but y not null
    if (y == null) return false;      // because x not null
    if (Object.ReferenceEquals(x, y) return true;
    if (x.GetType() != y.GetType()) return false;

    // compare all properties one by one:
    return x.Id == y.Id
        && x.Date == y.Date
        && ...
}

For GetHashCode is one rule: if X equals Y then they must have the same hash code. If not equal, then there is no rule, but it is more efficient for lookups if they have different hash codes. Make a tradeoff between calculation speed and hash code uniqueness.
In this case: If two Orders are equal, then I am certain that they have the same Id. For speed I don't check the other properties.
protected override int GetHashCode(Order x)
{
    if (x == null)
       return 34339d98; // just a hash code for all null Orders
    else
       return x.Id.GetHashCode();
}


text:
Q: kth smallest inetger value? Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct
def kthSmallest(self,arr,k):
    def k1(arr):
         res=arr[0]
         for i in range(1,len(arr)-1):
            if res>arr[i]:
                res=arr[i]
         return res
    if k==1:
        k1(arr)
    elif k==2:
        a=k1(arr)
        arr.remove(a)
        return k1(arr)

    else:
        for i in range(k-1):
          a=k1(arr)
          del a
        return k1(arr)
l=[7,10,4,3,20,15]
k=3
print(kthsmallest(l,k))

A: An easy way is to sort the array (or in your case, the list)
kthsmallest = sorted(arr)[K-1]

A: Why not just do it by sorting the array?
def kthSmallest(arr, k):
    arr.sort(reverse=False)
    return arr[k - 1]


text:
Q: How to fix Golang nw_path_close_fd Failed to close guarded necp fd 6 [9: Bad file descriptor] Hello I have a simple Go app running on macOS Mojave 10.14.4 with go version go1.15 darwin/amd64

import (
    "net/http"
    "os/exec"
)

func main()  {
    _, _ = http.Get("https://stackoverflow.com/")
    exec.Command("ls").Start()
}

It runs without any errors but if you run it while having the Console app you will see the following error logged from /usr/lib/libnetwork.dylib:
nw_path_close_fd Failed to close guarded necp fd 6 [9: Bad file descriptor]

The error gets triggered by the line exec.Command("ls").Start(), you can use a breakpoint or put it inside a loop to see it occur every time that line executes. Anyone knows what could be causing this and how to fix it?
Note: it does not happen with all URLs, for example https://www.facebook.com does not trigger the error.
Update: An additional detail, the error also doesn't show if I compile that app with go1.11.13


text:
Q: Accessing the currently selected element's content in a html(val) statement in jQuery? I have a several links whose text content I'd like to replace with a automatically generated image based on the text content.
So currently it looks like this:

The Text in Question

and I would like to have either

or

How do I access the element in question inside a .replaceWith or .html so that I can get the text content?

A: try this
$(".mLink").each(function (i) {

   var thisText = $(this).find(".mText").text();
   $(this).html("");

});

A: Using localized selectors
$(".mLink").each(function() {
    var text = $("span", this).text();
    $("span", this).replaceWith("");
});

A: $(function() {
    var mySpan = $('a.mLink span.mText');
    var text = mySpan.text();
    var link = text.split(' ').join('+');

    mySpan.replaceWith($(""));
});

Working Demo here
Code from demo
$(function() {

    $('#button').click(function() {

      $('a.mLink span.mText').each(function() {
        var text = $(this).text();
        var link = text.split(' ').join('+');
        $(this).replaceWith($(""));
      });

    });
});

A: Try something like this...
$(".mText").each(function(){
  var url = "/ImageTextHandler.ashx?message=" + escape($(this).text());
  var image = $("");
  image.attr("src") = url;
  image.attr("alt") = $(this).text();
  $(this).text("");
  $(this).append(image);
});


text:
Q: Replace number with last four digits of it I want to replace seven or more digits number with the following pattern.
1234567 to 4567/1234567
I'm using the following regex for matching the number (\d*(\d{4})) and replace it with the $2/$1
Is there any efficient way to do this?

A: A more efficient way is (\d+(\d{4})) since when you have less than five digits, you don't need to make anything. To be more precise you can use character classes with ranges since you use only ascii digits: ([0-9]+([0-9]{4})) (\d may indeed contain all kinds of digits like ٢ if \d is seen in a unicode meaning).
I don't see a better structure for the pattern. But if you have few digits (less than nine), using a non-greedy quantifier may be better:
([0-9]+?([0-9]{4}))


text:
Q: Facebook integration and event fetching in ios Hi I am working in xcode 6.4.
I am trying to create an application which integrate with Facebook.I want to fetch the event details of the user. That is, I want event_name, place, time, number of friends going and their details. I found many answers for this problem here and I tried them. But I couldn't build the app with that much of information. Please give me a detailed solution for the same.
[FBRequestConnection startWithGraphPath:@"me/events"
     parameters:@{@"fields":cover,name,start_time,end_time"}  HTTPMethod:@"GET"
     completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
     if (!error)
     {
         NSLog(@"event_name%@",[result objectForKey:@"name"]);
         NSLog(@"start_time%@",[result objectForKey:@"start_time"]);
         NSLog(@"end_time%@",[result objectForKey:@"end_time"]);}
     else
     {
         NSLog(@"%@", [errolocalizedDescription]);
     }
}];


text:
Q: Explain Build.scala in play framework Can somebody explain the syntax for Build.scala in detail?  For example, I have the following Build.scala:
import sbt._
import Keys._
import play.Project._

object Build extends sbt.Build {

   val appName         = "myapp"
   val appVersion      = "1.0"

   val appDependencies = Seq(
      "postgresql"    %   "postgresql"        % "9.1-901-1.jdbc4",
      javaCore,
      javaJdbc,
      javaEbean,
      "org.json"      %"org.json"             % "chargebee-1.0",
      "org.reflections" % "reflections" % "0.9.8",
      "org.mockito"   %   "mockito-all"       % "1.9.5" % "test"
    )

    val main = play.Project(appName, appVersion, appDependencies).settings(
      libraryDependencies += "com.jolbox" % "bonecp" % "0.8.0-rc2-SNAPSHOT",
      resolvers += Resolver.url("sbt-plugin-snapshots", new URL("http://repo.scala-sbt.org/scalasbt/sbt-plugin-snapshots/"))(Resolver.ivyStylePatterns),
      resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/"
    )

}

How do I match the appDependencies with the resolvers? Or how do I know what resolvers I need to add for what appDependencies? Where do I look in the resolver's repo? What is libraryDependencies? How are they different from appDependencies?
Thanks.

A: There are a few things we need to disentangle here.
Let's first distinguish between an sbt build file and Build.scala. While the build file is exactly like a Maven pom or a Gradle build file, think of Build.scala as a build capability with the full power and expressiveness of Scala because it is a Scala class like any other. I believe the gap between the two has narrowed though with the latest version of sbt.
Now in both sbt and Build.scala, you have the notion of library dependencies, which are the jar libraries containing code you can use for your projects. These libraries can be found in lots of places--Maven repositories, the local file system, etc. You use resolvers to specify those locations.
So you tell both which jars you need and where to find them.
As for appDependencies, that's not actually a thing. As I said, Build.scala is a class like any other, and appDependencies is just a variable name. It just makes sense to use that name because that Seq is what you will pass to the Project constructor.


text:
Q: how to get Cursor Invisbile or change focus in out of DIV I want cursor to be active only inside div and invisible outside of this div. How to do this?
I am using jQuery drag and drop functionality. When I drag its move all over the browser. I need to fix some particular height and width drag works only the particular fixed size how to do this?

A: Set cursor:none to body, html and cursor: default on your div

body,html{
  cursor: none;
  }
#cursor{
  cursor: default;
  background: red;
  width: 100px;
  height:100px;
  position:absolute;
  top:20px;
  left:20px;
  }

A: a solution would be the following:
css
div {cursor: auto }

* { cursor: none; }

However, how would the user find the div if they cannot see the pointer???

A: body {
  cursor: none;
}

div {
  cursor: auto;
}

should do the trick!

A: The CSS property that can be used is:
element.style {
   cursor: none;
}

Here is sample code

.nocursor {
      cursor: none;

      padding: 2em;
      border: 1px solid red;
    }

      When you mouse hover in div class,cursor will be hide


text:
Q: Pass data from the pipeline to views in Django Python Social Auth I was reading the documentation of Python Social Auth and got curious about the section of Interrupting the Pipeline (and communicating with views).
In there, we see the following pipeline code
In our pipeline code, we would have:

from django.shortcuts import redirect
from django.contrib.auth.models import User
from social_core.pipeline.partial import partial

# partial says "we may interrupt, but we will come back here again"
@partial
def collect_password(strategy, backend, request, details, *args, **kwargs):
    # session 'local_password' is set by the pipeline infrastructure
    # because it exists in FIELDS_STORED_IN_SESSION
    local_password = strategy.session_get('local_password', None)
    if not local_password:
        # if we return something besides a dict or None, then that is
        # returned to the user -- in this case we will redirect to a
        # view that can be used to get a password
        return redirect("myapp.views.collect_password")

    # grab the user object from the database (remember that they may
    # not be logged in yet) and set their password.  (Assumes that the
    # email address was captured in an earlier step.)
    user = User.objects.get(email=kwargs['email'])
    user.set_password(local_password)
    user.save()

    # continue the pipeline
    return

and the following view
def get_user_password(request):
    if request.method == 'POST':
        form = PasswordForm(request.POST)
        if form.is_valid():
            # because of FIELDS_STORED_IN_SESSION, this will get copied
            # to the request dictionary when the pipeline is resumed
            request.session['local_password'] = form.cleaned_data['secret_word']

            # once we have the password stashed in the session, we can
            # tell the pipeline to resume by using the "complete" endpoint
            return redirect(reverse('social:complete', args=("backend_name,")))
    else:
        form = PasswordForm()

    return render(request, "password_form.html")

Specially interested in the line
return redirect(reverse('social:complete', args=("backend_name,")))

which is used to redirect the user back to the pipeline using an already stablished backend.
We can see earlier in that page a condition that's used to check which backend is being used.
def my_custom_step(strategy, backend, request, details, *args, **kwargs):
    if backend.name != 'my_custom_backend':
        return
    # otherwise, do the special steps for your custom backend

The question is, instead of manually adding it in the args=("backend_name,"), how can the pipeline communicate the correct backend to the view?

A: One can simply add in the pipeline
request.session['backend'] = backend.name

and then the view becomes
backend_name = request.session['backend']
return redirect(reverse('social:complete', args=(backend_name)))


text:
Q: Python CSV reader/writer handling quotes: How can I wrap row fields in quotes? (Getting triple quotes as output) I have a problem with the csv reader and writer in python.  Whenever I try to take one CSV file and par down the number of columns from roughly 37 to 6, this is the kind of output I am getting. Example of one row:
0,"JOHNSON, JOHN J.",JOHN J. JOHNSON,TECH879,INSPECTION TECHNICIAN,MOTOR VEHICLE INSPECTION UNIT
Notice the second field is quoted.  This is what I see when I view it in a text editor.  I want all of the fields to be quoted.  There is a problem.  First, my code, one example of it:
import os
import csv
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
with open(os.getcwd()+'/dl1/filepfr062220155.csv','w') as fp:
identity = 0
for i in alpha:
    csvholder = open(os.getcwd()+'/dl1/pfr/'+i+'.csv','rb')
    spamreader = csv.reader(csvholder, delimiter=',')
    for row in spamreader:
        if 'Sort Name' in row[0]:
                pass
        else:
                ###SEE HERE###
                data = [[str(identity),row[0],row[1],row[2],row[3],row[37]]]
                identity+=1
                a = csv.writer(fp,delimiter=',',quotechar='"')
                a.writerows(data)

The problem is, about where I have marked "###SEE HERE###, I've tried wrapping the unquoted fields in quotes like so:
data = [['"'+str(identity)+'"',row[0],'"'+row[1]+'"','"'+row[2]+'"','"'+row[3]+'"','"'+row[37]+'"']]

But that gives me output that looks like this, with triple quotes, and that is not acceptable...like so:
"""4""","JOHNSON, JOHN W.","""JOHN W. JOHNSON""","""TEC5681""","""INSPECTION TECHNICIAN""","""MOTOR VEHICLE INSPECTION UNIT"""
The original form of these rows was likes this:
"NAME","NAME","NAME","NAME" and so on...
So I don't know why only the one field was quoted in the final output.  I either need all of the fields quoted or none of them quoted.
I have already tried going with and without "quotechar" on both the reader and the writer, all such combinations.
So if you could either tell me how to retain the original quoting from the original file or how to solve this triple quoting problem so I can reformat manually, that would be great.

A: quotechar only indicates what character the writer should use for quoting. It's quote=csv.QUOTE_ALL that you need.  Create your writer like this:
a = csv.writer(fp, quoting=csv.QUOTE_ALL)

quoting defaults to csv.QUOTE_MINIMAL, meaning that it will only quote fields if they contain the delimiter, which is why it's only quoting "JOHNSON, JOHN J.".
(Note that I left out delimiter since it already defaults to ',' but of course it won't hurt you to define it explicitly if you like.)
quoting and other dialect parameters are keyword arguments to csv.writer, and are described in the Python documentation for the csv module, under section 13.1.2.


text:
Q: Filemaker no multiplica campos Tengo un problema serio con Filemaker.
Por alguna razón, no quiere hacer operaciones incluso dentro de la misma tabla.
Los dos campos están en la misma tabla y son de tipo numero.

Les agradezco su respuesta.

A: puedes probar desmarcar la opción 'No evaluar si todos los campos indicados están vacíos', después de esto recordar que el campo se actualizará solo al manipular los dos campos indicados, pero no es un campo calculado, es número con cálculo por lo cual no tiene activador directo, si pruebas usar el evento con una modificación en la tabla puede que sea más fácil que se ejecute cuando lo corras ejemplo:
crear campo update - timestamp - 'modify timestamp' por defecto
en tu campo de la BD IF(update; Cantidad * Precio ; Importe )
Recordar que es probable que si estás haciendo ese cálculo desde una tabla encabezada sobre una tabla detalle puede que no se ejecute correctamente al no ser calculado, por eso es recomendable, al menos a mi parecer, hacer este tipo de cálculos en un script que se ejecute como trigger dentro de ambos campos de cantidad y precio en tu layout.


text:
Q: Bind to extension method in WPF I have a simple class in C#:
public class Dog {
    public int Age {get; set;}
    public string Name {get; set;}
}

and I created an extension Method like this :
public static class DogExt {
    public static string BarkYourName(this Dog dog) {
        return dog.Name + "!!!";
    }
}

Is there any way how to bind result of the BarkYourName method to a wpf component?
Basically : is there any way hwo to bind it to an extension method?

A: Programming is the logical IQ game.
Binding with MethodName is not possible in WPF as the Binding engine only works with Properties. Although, you can use some tricks.
Here are some ways to accomplish this.

*

*Add an extension method to the get accessor of the property, like this
private string _name;
public string Name
{
    get { return _name.BarkYourName(); }
    set
    {
        _name = value;
        OnPropertyChanged("Name");
    }
}

*Add a converter to change the effect of the Name property, like this
public class NameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return "!!!";

        return value.ToString().BarkYourName();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public static class StringExt
{
    public static string BarkYourName(this string str)
    {
        return str + "!!!";
    }
}

A: No way to bind to methods. You can create the property in Dog class like below and bind to it
public string NameEx
    {
        get
        {
            return this.BarkYourName();
        }
    }

and if you want to keep Name and NameEx in sync, just raise the PropertyChanged-event for NameEx also in the setter of the Name-property.

A: No, you cannot bind to an extension method. You can bind to the Name-property of the Dog-object and use a converter though.
To create a converter create a class implementing the IValueConverter interface. You will need a one-way conversion only (from the model to the view) so will need to implement the Convert method only. The ConvertBack method is not supported by your converter and thus throws a NotSupportedException.
public class NameToBarkConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var dog = value as Dog;
        if (dog != null)
        {
            return dog.BarkYourName();
        }
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Then you can use your converter as follows:
<Grid>
    <Grid.Resources>
        <NameToBarkConverter x:Key="NameToBarkConverter" />
    </Grid.Resources>
    <TextBlock Text="{Binding Name, Converter={StaticResource NameToBarkConverter}}" />
</Grid>

For more information on converters see MSDN: IValueConverter.


text:
Q: Fix the display of output My code works perfectly fine, but I am having trouble trying to make the output look like the one on the picture. I need to have the exact same spaces (exact display). I don't need to alter colors, just spaces and display. Please help! PICTURE
name = input("Enter employee's name: ")

hours = float(input("Enter number of hours worked in a week: "))

payRate = float(input("Enter hourly pay rate: "))

fedTaxWithholdingRate = float(input("Enter federal tax withholding rate (ex. 0.12): "))

stateTaxWithholdingRate = float(input("Enter state tax withholding rate (ex. 0.06): "))

grossPay = hours * payRate

fedTaxWithholding = grossPay * fedTaxWithholdingRate

stateTaxWithholding = grossPay * stateTaxWithholdingRate

totalDeduction = fedTaxWithholding + stateTaxWithholding

netPay = grossPay - totalDeduction

print("Employee Name: " + name)

print("Hours Worked: " + str(hours))

print("Pay Rate: $" + str(payRate))

print("Gross Pay: $" + str(grossPay))

print("Deductions:\n")

print(" Federal Withholding (" + str(fedTaxWithholdingRate * 100) + \
 "%): $" + str(int(fedTaxWithholding * 100) / 100.0))

print(" State Withholding (" + str(stateTaxWithholdingRate * 100) + "%):" + \
 " $" + str(int(stateTaxWithholding * 100) / 100.0))

print(" Total Deduction:" + " $" + \
 str(int(totalDeduction * 100) / 100.0))

print("Net Pay:" + " $" + str(int(netPay * 100) / 100.0))

A: add " " * number_of_spaces + "your string" in some places


text:
Q: Difference between angularjs module and java package I'm Java lecturer and build AngularJS lecture for JAVA programmers.
As I can see in the documentation of w3schools:

Modules define applications. All application controllers should belong
  to a module.
Modules make your application more readable, and keep the global
  namespace clean.

If I understand angularJS module has the same meaning like Java package.
Is it true or I miss something?


text:
Q: Dynamic sized array of pairs: Setting values for first/second I keep getting errors "subscript requires array or pointer type" when working with an array of pairs. I've looked at all the other threads with similar problems, but have been unable to resolve it.
I dynamically declared an array of pairs which looks like:
pair<T, int> *m_Array;

And set the array size with:
m_Array = new pair<T, int>[c];

Now what I am failing to do is access the first and second of the pair, in an index of the array. I get the error when I try to do things like this.
for (int i = 0; i < m_Size; i++) {
    m_Array->first[i] = rhs.m_Array->first[i];
    m_Array->second[i] = rhs.m_Array->second[i];
}

It intuitively seems like it should be more like the following code, but my IDE does not like me having m_Array[i]
for (int i = 0; i < m_Size; i++) {
    m_Array[i]->first = rhs.m_Array[i]->first;
    m_Array[i]->second = rhs.m_Array[i]->second;
}

A: You're nearly there.
If m_Array is a pointer to some pairs, then m_Array[0] is the first pair; then m_Array[0].first is the "first" member of that first pair.
There is no need for the dereferencing member access operator ->, as the subscription [i] has already dereferenced for you (that is, m_Array[i] means *(m_Array + i)). So you just need the normal member access operator..
So:
for (int i = 0; i < m_Size; i++) {
    m_Array[i].first  = rhs.m_Array[i].first;
    m_Array[i].second = rhs.m_Array[i].second;
}

Or you could skip all this trouble and just write:
for (int i = 0; i < m_Size; i++) {
    m_Array[i] = rhs.m_Array[i];
}

Or you could skip that too and change from new and arrays to a nice std::vector, then have it do all the work for you.


text:
Q: MySQL Server 8.0 cannot change tmpdir Configuration file: C:\ProgramData\MySQL\MySQL Server 8.0\my.ini

Here is the screen when I click "Options File" from MySQL Workbench CE.
As you can see, the configuration file is correct and tmpdir is displaying correctly here.

However when I run this query SHOW VARIABLES LIKE 'tmpdir';, here is the result

I tried shutting down MySQL80 in services, then changing my.ini, then starting the service back up.
Any idea why this wont update?


text:
Q: Put nested field result into single string I've got this query (nevermind the fact it's not properly normalised):
Select Name, (Select FLB_Inbound_Flight_No__c, FLB_Outbound_Flight_No__c
              FROM Flight_Bookings__r)
FROM Opportunity
Where id='00XX00000XXXXXXXXX'

And results:
[{"FLB_Inbound_Flight_No__c":"BA713","FLB_Outbound_Flight_No__c":"BA712"},
{"FLB_Inbound_Flight_No__c":"BA713","FLB_Outbound_Flight_No__c":"BA712"},
{"FLB_Inbound_Flight_No__c":"LX332","FLB_Outbound_Flight_No__c":"LX317"}]

What I want to have (must be deduped):
string Flight_No = 'BA713, BA712, LX332, LX317'

Visualforce page prints the results in the following manner:
<apex:column >
    <apex:facet name="header">
        Check Out Date
    </apex:facet>
    <apex:outputField value="{!o.opportunity.O_CheckOut_Date__c}" />
</apex:column>

I presume I will need some sort of loop to assign all the values to one string?
My trouble is that the query is executed in the following way (SOQL query is built based on several conditions):
for(Opportunity opp : database.Query(strQry)){
    BulkEmail b = new BulkEmail();
    b.opportunity = opp;
    listBulkEmail.add(b);
}

Any ideas? Perhaps I should post more code?

A: UPDATE: use of the wrapper class
Apex:
public with sharing YourClass{

    public List<MyWrapper> allOpps { get; set; }

    public YourClass(){
        allOpps = new List<MyWrapper>();
    }

    public class MyWrapper{
        public Opportunity opp { get; set; }
        public String flightNumbers { get; set; }

        public MyWrapper(Opportunity o, String s){
            this.opp = o;
            this.flightNumbers = s;
        }
    }

    for(Opportunity opp : database.Query(strQry)){
        BulkEmail b = new BulkEmail();
        b.opportunity = opp;
        listBulkEmail.add(b);

        if(!opp.Flight_Bookings__r.isEmpty()){
            String numbers = '';
            for(Flight_Booking__c fb : opp.Flight_Bookings__r){
                if(!numbers.containsIgnoreCase(fb.FLB_Inbound_Flight_No__c)){
                    numbers += fb.FLB_Inbound_Flight_No__c + ',';
                }
                if(!numbers.containsIgnoreCase(fb.FLB_Outbound_Flight_No__c)){
                    numbers += fb.FLB_Outbound_Flight_No__c + ',';
                }
            }

        }
            else {
                numbers = 'There is no data.';
            }

            allOpps.add( new MyWrapper(opp, numbers) );
    }
}

Visualforce page:
<apex:pageBlockTable value="{!allOpps}" var="o">
    <apex:column value="{!o.opp.Name}" />
    <apex:column headerValue="Flight numbers">
        <apex:outputText value="{!o.flightNumbers}">
    </apex:column>
</apex:pageBlockTable>

The easiest way to do this is use your loop and add another loop to collect values from the subquery:
String Flight_No = '';

for(Opportunity opp : database.Query(strQry)){
    BulkEmail b = new BulkEmail();
    b.opportunity = opp;
    listBulkEmail.add(b);

    if(!opp.Flight_Bookings__r.isEmpty()){
        for(Flight_Bookings__c fb : opp.Flight_Bookings__r){
            if(!Flight_No.containsIgnoreCase(fb.FLB_Inbound_Flight_No__c)){
                Flight_No += fb.FLB_Inbound_Flight_No__c + ',';
            }
            if(!Flight_No.containsIgnoreCase(fb.FLB_Outbound_Flight_No__c)){
                Flight_No += fb.FLB_Outbound_Flight_No__c + ',';
            }
        }
    }
}


text:
Q: Accessing CodeIgniter library through ExpressionEngine I'm not sure if this is possible, but various posts in the ExpressionEngine forums and in the documentation suggest that I should be able to let ExpressionEngine know what's going on in the CodeIgniter foundation that it's built on.
So, in light of that, I've got a CodeIgniter app, and an ExpressionEngine site. The /system directory is structured like this:
/system

*

*/system/codeigniter

*/system/codeigniter/application (this is my existing CodeIgniter application)

*/system/codeigniter/system (this is the same CI folder that EE runs from)

*/system/expressionengine

*... (this is the normal EE - templates, add-ons, etc.

I'm fairly new to ExpressionEngine, but my understanding was that I could use this setup to built an EE module that would integrate well with CodeIgniter.
Currently, I have a module setup, and a method in it that does this, just as a starting point:
function __construct()
{
    $this->EE =& get_instance();
    $this->CI =& get_instance();
    $this->auth =& $this->CI->load->library('mylibrary');
}

But then it doesn't recognize the library when I load the module (this is all happening inside the EE control panel, at this point, just so I can make a connection between the two). Says it doesn't exist. Is there anything I can do to make this connection, or am I going the wrong direction entirely?
Thanks,
Jonathan

A: Okay, thanks to http://expressionengine.com/forums/viewthread/208140/ I have an answer I think I can build upon.
Here's how it works, for posterity's sake:

EE and your module don't know at all about your system/codeigniter/application folder. Try this, it > might work:
$this->EE =& get_instance();
$this->EE->load->add_package_path(BASEPATH.'../application/');
$this->EE->load->library('mylibrary');
$this->EE->mylibrary->do_stuff();

From there I was able to load my library, but it had issues loading its language file. The same thread gave an answer to that, as well. This code goes into the CI library file, and EE translates it as it loads.
$this->ci->lang->load('mylangfile', '', FALSE, TRUE, BASEPATH.'../application/');

A: In the past I've written simple wrapper add-ons for EE to access the CodeIgniter helpers, etc.  Here's an example of a simple wrapper add-on.
Another option, it should be possible to this with PHP, which means you'll need to enable PHP in your template. In short, you load the helper/library/etc and then call the method you want.   More info on how to do that in the EE docs.

A: You should simply put your library in /third_party/my_addon/libraries/ folder, then load it like so:
function __construct()
{
    $this->EE =& get_instance();
    $this->auth = $this->EE->load->library('../third_party/mhy_addon/libraries/mylibrary');
}


text:
Q: Symfony is-a database schema So I am new to symfony and am trying to make a is-a relationship between several tables. I have a media table that has a id field that is the primary key. I then except to have 2 or more additional tables that are "subclasses" of this table such as an article or event table. These are subclasses of the media table and I put a media_id field in these tables that have FK constraints with the media table and are primary keys of the specific tables. However when I build the module based off of this model, this relationship does not hold.
For example, when I try adding an article, I have to add a media item first, but then in the create article form, there is no way to add a media id to it.
Any ideas?
Thanks!

A: Use inheritance instead of a relationship:
detect_relations: true
Media:
  columns:
  #columns for all sub classes

Event:
 columns:
 # other columns for Event Subclass
 inheritance:
    extends: Media
    type: column_aggregation
    key_field: type
    key_value: 1

Other:
 columns:
 # other columns for Other Subclass
 inheritance:
    extends: Media
    type: column_aggregation
    key_field: type
    key_value: 2


text:
Q: How can I import a partition from one table into another in Oracle? I would like to know if the following steps are possible and how fast this is:

*

*Create a partition named part1 in Table A

*Drop partition part1 in Table B

*Import the Table A partition part1 into Table B

Can you provide me with an example if it is possible indeed? Or any resources I can look at?
Note that the tables would have the exact same structure.

A: You can do something similar with the ALTER TABLE ... EXCHANGE PARTITION command. This would exchange a single partition with a table that has the same structure.
A little example:
/* Partitionned Table Creation */
SQL> CREATE TABLE table_a (
  2     ID NUMBER PRIMARY KEY,
  3     DATA VARCHAR2(200)
  4  )
  5  PARTITION BY RANGE (ID) (
  6     PARTITION part100 VALUES LESS THAN (100),
  7     PARTITION part200 VALUES LESS THAN (200)
  8  );

Table created

/* Swap table creation */
SQL> CREATE TABLE swap_table (
  2     ID NUMBER PRIMARY KEY,
  3     DATA VARCHAR2(200)
  4  );

Table created

SQL> INSERT INTO swap_table SELECT ROWNUM, 'a' FROM dual CONNECT BY LEVEL <= 99;

99 rows inserted

SQL> select count(*) from table_a partition (part100);

  COUNT(*)
----------
         0

This will exchange the partition part100 with the transition table swap_table:
SQL> ALTER TABLE table_a EXCHANGE PARTITION part100 WITH TABLE swap_table;

Table altered

SQL> select count(*) from table_a partition (part100);

  COUNT(*)
----------
        99


text:
Q: How do I focus on the next field by testing event.which == 13 without leaving a trailing \n in the current field? $("#title").keypress(function(event){
    if(event.which == 13){
        $("#nextField").focus();
    }
});

Q: How do I focus on #details with-out leaving a trailing \n in #title's value?
Failed attempt:
$("#title").keypress(function(event){
    if(event.which == 13){
        $(this).val($(this).val().replace(/\n/g,""));
        $("#nextField").focus();
    }
});

A: What you want is event.preventDefault();
$("#title").keypress(function(event){
    if(event.which == 13){
        $("#details").focus();
        event.preventDefault();
    }
});


text:
Q: Template function in template class Related to this
Can't get the following to compile and I don't really understand why.
Codebolt Code
Snippet here
#include <vector>
#include <string>

template<typename T>
class A
{
    using func_type = bool(int const&);

    template<func_type U, func_type X>
    [[using gnu:cold]]void example(std::vector<std::string>&&);
};

template <typename T>
template <typename A<T>::func_type U, typename A<T>::func_type X>
void A<T>::example(std::vector<std::string>&&)
{

}

Thank you

A: If you don't want to use the func_type anywhere outside of your class. Then you should change it to
using func_type = bool(*)(int const&);
Remember that the syntax is similar to emplying typedef for function pointers.


text:
Q: How to verify that code reviewed patch file is exactly what is committed into SVN repository We have a code review process in place where a developer sends out a patch file with his changes to the team. After reviewing it, he is instructed to commit or make changes and resend.
How can we ensure that what has been "committed" is exactly what has been "approved" - i.e., if he makes subsequent changes without approval and commits those, how can I detect those?
I have the original 'patch file' at my end, but:

*

*How can I 'generate' something similar between the two committed versions and

*Is it viable to compare those two files?

A: The easiest way is that The reviewer commit the changes he approved. I've seen some old fashion team (a while ago) where only the project manager could commit to production repository. The thing is, as he has to commit too much stuff he didn't really check anything so that was a bit pointless.

A: The simplest solution would be to put such patches to a branch which mean the developer will check in the code on the branch. Than a reviewer can check the code and merge the code back to a particular integration line. This makes sure the code checked in is exactly what has been checked. Furthermore this approach has the advanctage the suggestion which have been made will be documented in the version control as well.

A: Reviewer should be a committer as well to make sure he commits the same he reviewed and approved.

A: I am guessing you could do this by applying the patch on the old revision and then comparing the same against the latest version of code for difference.
You could use svn diff for this.
You probably wanna take a look at this answer: How to make svn diff produce file that patch would apply, when svn cp or svn mv was used?


text:
Q: Android seekbar easy way to display the progress when onProgressChanged is triggered Is there any easy way to show some kind of flag or Toast-like (not a Toast..) indication when the user is dragging the seekbar? I've implemented OnSeekBarChangeListener like this
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    int position = seekBar.getProgress();
    service.seekToPosition(position);
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromUser) {
    if(fromUser){

    }
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub

}

it gets the seek bar progress after the user has stopped the drag movement and sets the current music playback to that position.
In the onProgressChanged method i'd like to display the seekbar progress while the user is dragging the seekbar.
Is there a simple way to do this?
Marcus

A: I would just create a framelayout or relativelayout. Put a textview in front of your view and make the background black, maybe a bit see through and the textcolor white. Set visibility to false. When onProgressChanged is called make it visible and update the textview accordingly to the seekbar. When you release the seekbar set visibility to false again.


text:
Q: UIButton change background when tapped (programmatically) I have a custom UIButton but I am not able to make changing background or text color based on a quick tap. If something works, it's only on long press:
    buton.isUserInteractionEnabled = true
    buton.setTitle("text_normal", for: .normal)
    buton.setTitle("text_highlighted", for: .highlighted)
    buton.setTitle("text_selected", for: .selected)
    buton.setTitle("text_focused", for: .focused)

The only text I can get is "text_highlighted" after holding the button ~1 second. But nothing happens on short tap.
But the action is triggered correctly:
let tap2 = UITapGestureRecognizer(target: self, action: #selector(handleTap))
buton.addGestureRecognizer(tap2)

@objc func handleTap(sender: UITapGestureRecognizer) {
    print("click")
}

What I tried:
Adding custom
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
...

which is also triggered later. And combining with tocuhesEnded didn't change the color temporarily as well (maybe it was too quick).
I can't use UIButton(type: .system) as well - it's not system styled button.
Similar as with changing text this is not working as well:
    self.setTitleColor(UIColor.gray, for: .normal)
    self.setTitleColor(UIColor.yellow, for: .selected)
    self.setTitleColor(UIColor.yellow, for: .highlighted)
    self.setTitleColor(UIColor.yellow, for: .focused)

I can see yellow only when long pressed. I am looking for something like this, but it needs to work on quick tap as well.
Custom button is modifying layoutSubviews(), but not colors. Custom button contains default image and label. Whole button has rounded corners. But overall nothing special is in there.
I am not using any storyboard or XIB - everything is in Swift 4 programatically.
The button is supposed to lead to another ViewController, but I want to see the immediate feedback on click. Something like when created from storyboard: https://youtu.be/lksW12megQg?t=3m25s - not even simple alpha change works for me right now.

A: check isselected property of uibutton if button is selected then change the background color of button

A: Jen Jose was right - there was a problem with my parent class which was 'eating up' my touches. I confirmed this when moving it to different ViewController + I had the same issue with table, which couldn't handle touch events (https://stackoverflow.com/a/9248827/1317362)
EDIT:
To be precise - this button was in a UIScrollView.
Adding scrollView.delaysContentTouches = NO; solved the issue completely.
Details: https://stackoverflow.com/a/16650610/1317362


text:
Q: Code Uploaded with VSCode+PlatformIO Is Performing Dramatically Slower Than with Arduino IDE I am trying to transition a project to PlatformIO and the same code is performing very differently depending on which IDE I use to upload to the board.
I am using the FastAccellStepper library to control a stepper with an ESP32 dev board.
I calculate the steps required to run the stepper for a period of time, say 10sec.
Code uploaded with the Arduino IDE runs for 10s, but the stepper runs slower and longer (~30s) when uploaded with PlatformIO.
I am at a loss of what to try to fix this issue.  Is there something PIO does with debugging/interrupts that can be messing up the timing of FastAccellLibrary?  Is the board clock speed settable in PIO somewhere?
;platformio.ini
platform = espressif32
board = ttgo-lora32-v1
framework = arduino
lib_deps =
    bodmer/TFT_eSPI@^2.3.3
    lennarthennigs/Button2@^1.2.0
    gin66/FastAccelStepper@^0.8.0
monitor_speed = 115200

Thanks for any help.

A: Try adding to platformio.ini in the relevant section:
board_build.f_cpu = 240000000L
and use the latest version.


text:
Q: Apache Flink: Merge two DataStreams with a CoFlatMapFunction I'm trying to merge two streams of the same data type. I saw the CoFlatMapfunction and tried it out, but I'm getting the following error:

"unspecified value parameters".

The code is written in Scala
val eventsTypeOne: DataStream[Option[Event]] =  patternStream1.select(pattern => selectFn1(pattern.toMap))
val eventsTypeTwo: DataStream[Option[Event]] = patternStream2.select(pattern => selectFn2(pattern.toMap))

eventsTypeOne.connect(eventsTypeTwo).flatMap(new CoFlatMapFunction[Option[Event], Option[Event], Option[Event]] {
  override def flatMap1(eventTypeOne: Option[Event], out: Collector[Option[Event]]): Unit = {
    out.collect(eventTypeOne)
  }

  override def flatMap2(eventTypeTwo: Option[Event], out: Collector[Option[Event]]): Unit = {
    out.collect(eventTypeTwo)
  }
})
}

How can I use the CoFlatMapFunction correctly? Or is there a more elegant way to merge two data streams?
Thanks in advance!

A: You can achieve the same functionality by using a union() operator. Union allows to merge two streams of the same type.


text:
Q: Proving that if |domain (f)|= |codomain (f)| where f:A→B is surjective, it will be injective too I thought about going to prove this by contradiction.
Assume that the domain and the codomain are finite.
Assuming for contradiction that if f(a)=f(b);a≠b;a,b∈A
Because of |A|=|B|, A and B are finite, there exists e∈B for which there does not exist d∈A: f(d)=e
Therefore f is not surjective which leads us to the contradiction. So f must be injective too.
The issue is that I am not sure if this proof is correct formulated as I am a beginner. So I would like to see opinions or ways about how can I fix this, thanks.


text:
Q: Eliminar numeros repetidos en un arreglo dinamico en C Si bien parece que no es un tema que no se haya hablado me encuentro con una situación particular que me gustaría me ayuden a saber por que ocurre.
La situación es que tengo un arreglo dinámico de números aleatorios los cuales pueden ser repetidos, si son repetidos debo pasarlo a otro vector dinámico (la longitud de este vector cambia en tiempo de ejecución y pensaba hacerlo con realloc), la particularidad es que necesito hacerlo con punteros y estructuras y no comprendo por qué hay un if en el que no esta entrado por mas que estoy viendo que cumple la condición con un if.
Otro error que no se por qué ocurre es cuando quiero cambiar el tamaño nuevo del vector porque necesito que el vector que no contenga repetidos aumente en 1 su tamaño ya que estoy agregando un nuevo valor, proporciono el código que esta documentado, es un poco largo así que pongo solo las partes problemáticas y abajo dejo todo el código.
Brevemente la idea es que tenga un i que se quede parado en un valor del vector con repetidos (lo llamare vector 1) y compare con un j que se moverá por todo el vector sin repetidos (lo llamare vector 2) entonces si llega al final del j sin encontrar repetidos puedo hacer un realloc con el valor de i que encontré, de lo contrario si encontre el repetido salgo del while y voy al siguiente valor de i.
void sacar_repetidos(vector *a, vector2 *b)
{
  int i = 0;

  for (i = 0; i < a->size; i++)
  {
    int j = 0;
    while(j <= b->nuevo_size )
    {
      if(b->nuevo_size == 0) //no lo tengo que comprar con nada porque es el primero entonces lo aloco directamente
      {
        b->vec2 = malloc(1*sizeof(int));
        b->vec2[j] = a->vec[i];
        b->nuevo_size = 1; //este es el caso donde me obliga a poner el valor concreto, 1 pero no me deja escribir  b->nuevo_size = b->nuevo_size+  1; y no se por que
      }

      while (b-> vec2[j] != a->vec[i]  && j <= b->nuevo_size) //mientras el valor de vec2 sea distinto al vec y sea menos que el tamaño del vec2
      {
        printf(" %i",j); //imprimo para corroborar los valores de i y nuevo_size y veo que son los mismos efectivamente
        printf(" %i ",b-> nuevo_size);
        j++;
        printf(" %i ",a->vec[i]);
        printf("\n");

      }
      if (b-> nuevo_size == j ) //este es el if al que deberia entrar pero no lo hace por mas que veo que alcanza los valores que le estoy pidiendo
        {
          printf("entra");
          b-> nuevo_size = b-> nuevo_size + 1;
          b ->vec2 = realloc(b-> vec2, b -> nuevo_size);
        }
        if (b-> vec2[j] == a->vec[i]) //encontre un repetido en esa posicion de j
        {
          break;
        }

    }
  }
}

También dejo el código completo de ser necesario, disculpen si esta mal escrito, aun estoy practicando
#include <stdio.h>
#include<stdlib.h>

typedef struct
{
  int *vec;
  int size;
} vector;

typedef struct
{
  int *vec2;
  int nuevo_size;
}vector2;

void inicializar(vector *a, int tamaño_inicial)
{
  a->vec = malloc(tamaño_inicial * sizeof(int));
  a->size = tamaño_inicial;
}

void llenar(vector *a)
{
  int i = 0;
  for(i = 0; i < a->size; i++)
  {
    a->vec[i] = rand()%10;
  }
}

void mostrar(vector *a)
{
  int i = 0;
  for(i = 0; i < a->size; i++)
  {
    printf(" %i ",a->vec[i]);
  }
}

void vaciar(vector *a)
{
  free(a->vec);

}

void sacar_repetidos(vector *a, vector2 *b)
{
  int i = 0;

  for (i = 0; i < a->size; i++)
  {
    int j = 0;
    while(j <= b->nuevo_size )
    {
      if(b->nuevo_size == 0) //no lo tengo que comprar con nada porque es el primero entonces lo aloco directamente
      {
        b->vec2 = malloc(1*sizeof(int));
        b->vec2[j] = a->vec[i];
        b->nuevo_size = 1; //este es el caso donde me obliga a poner el valor concreto, 1 pero no me deja escribir  b->nuevo_size = b->nuevo_size+  1; y no se por que
      }

      while (b-> vec2[j] != a->vec[i]  && j <= b->nuevo_size) //mientras el valor de vec2 sea distinto al vec y sea menos que el tamaño del vec2
      {
        printf(" %i",j); //imprimo para corroborar los valores de i y nuevo_size y veo que son los mismos efectivamente
        printf(" %i ",b-> nuevo_size);
        j++;
        printf(" %i ",a->vec[i]);
        printf("\n");

      }
      if (b-> nuevo_size == j ) //este es el if al que deberia entrar pero no lo hace por mas que veo que alcanza los valores que le estoy pidiendo
        {
          printf("entra al if");
          b-> nuevo_size = b-> nuevo_size + 1;
          b ->vec2 = realloc(b-> vec2, b -> nuevo_size);
        }
        if (b-> vec2[j] == a->vec[i]) //encontre un repetido en esa posicion de j
        {
          break;
        }

    }
  }
}

void mostrar_sin_repetidos(vector2 *b)
{
  int i = 0;
  for(i = 0; i < b->nuevo_size; i++)
  {
    printf(" %i ",b->vec2[i]);
  }
}

int main(void) {
  vector v;
  vector2 nuevo;
  nuevo.nuevo_size = 0;
  inicializar(&v, 4);
  llenar(&v);
  printf("Vector original:");
  mostrar(&v);
  printf("\n");
  sacar_repetidos(&v, &nuevo);
  printf("Vector sin repetidos:");
  mostrar_sin_repetidos(&nuevo);
  printf("\n");
  printf("Tamaño del nuevo vector: ");
  printf("%i ",nuevo.nuevo_size);
  return 0;
}

Dejo una aclaración importante, si por algun motivo alguien quiere copiar y pegar el código para probar su funcionamiento o cualquier motivo probablemente tenga errores por el uso de la letra "ñ", solo fue usada en la función inicializar por lo que solo cambiándolo en ese lugar ¡ya debería funcionar para todos!
¡Gracias de antemano!
Edito: logre hacer funcionar mi código, para cualquiera que lo quisiese ver lo dejo a disposición.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct
{
  int *vec;
  int size;
} vector;

void inicializar(vector *vect, int tamaño_inicial)
{
  vect->vec = malloc(tamaño_inicial * sizeof(int));
  vect->size = tamaño_inicial;
}

void llenar(vector *vect)
{
  int i = 0;
  for(i = 0; i < vect->size; i++)
  {
    vect->vec[i] = rand()%10;
  }
}

void mostrar(vector *vect)
{
  int i = 0;
  for(i = 0; i <vect->size; i++)
  {
    printf(" %i ",vect->vec[i]);
  }
}

void vaciar(vector *vect)
{
  free(vect->vec);
  vect ->size = 0;
}

void add(vector *vect, int valor)
{
  int* ptr = (int*) realloc(vect->vec, vect->size + 30);
  vect->vec = ptr;
  vect->vec[vect->size++] = valor;

}

void sacar_repetidos(vector *original, vector *sin_repetidos)
{
  int i = 0;
  for (i = 0; i < original->size; i++)
  {
    int j = 0;
    int repetido = 0;

    for(j = 0; j < sin_repetidos->size && !repetido; j++) // gracias eferion por esta sintaxis
    {
      if (original->vec[i] == sin_repetidos->vec[j])
      {
        repetido = 1;
      }
    }
      if(!repetido)
      {
        add(sin_repetidos, original->vec[i]);
      }

  }
}

int main(void) {
  srand(time(NULL));
  vector v;
  vector nuevo;
  inicializar(&v, 25);
  llenar(&v);
  printf("Vector original:");
  mostrar(&v);
  printf("\n");
  inicializar(&nuevo, 0);
  sacar_repetidos(&v, &nuevo);
  printf("\n");
  printf("Vector sin repetidos:");
  mostrar(&nuevo);
  printf("\n");
  printf("Tamaño del nuevo vector: ");
  printf(" %i ", nuevo.size);
  vaciar(&v);
  vaciar(&nuevo);
  return 0;
}

A: Tu código es un baile desordenado de variables, índices y demás. Es complicado darte una respuesta concreta del motivo del fallo porque convergen varios problemas de diseño.
Un problema que tienes es que tu programa no genera realmente números aleatorios. No inicializas la semilla del generador de números aleatorios, luego siempre obtendrás exactamente los mismos resultados, sin importar cuántas veces ejecutes el programa.
Esto se soluciona con una simple línea de código:
srand(time(NULL));

Añadiendo esta línea antes del primer uso de rand() tendrá como efecto que tu programa empezará a generar secuencias diferentes en cada ejecución (salvo que consigas ejecutar el programa dos veces seguidas en el mismo segundo).
Por otro lado, variables con nombres como a, b, ... no aportan absolutamente nada. No ayudan a entender mejor el código y hacen que seas más propenso a equivocarte de variable. Acostúmbrate a usar nombres de variables que sean representativos.
Hablando del diseño de la aplicación, no hay ninguna necesidad de gestionar dos estructuras diferentes. Con un único struct te serviría:
typedef struct
{
  int *vec;
  int size;
} vector;

Pero quizás habría que añadir algo de información a esta estructura para poder usarla con más comodidad:
typedef struct
{
    int *vec;
    size_t size;
    size_t count;
} vector;

Con este cambio podemos saber cuántos elementos hay en la estructura.
Este diseño nos permite crear fácilmente un ecosistema de utilidades para trabajar cómodamente con la estructura:
// Inicializa un objeto de tipo vector
vector NewVector()
{
    vector vect;
    memset(&vect, 0, sizeof(vector));
    return vect;
}

// Libera la memoria asociada a un vector
void FreeVector(vector * vect)
{
    // Liberamos la memoria reservada
    free(vect->vec);

    // Reseteamos las variables de estado, para ser coherentes
    memset(vect, 0, sizeof(vector));
}

// Actualiza el vector para que sea capaz de almacenar un número de elementos dado
int SetCapacity(vector* vect, size_t capacity)
{
    if( capacity > vect->size )
    {
        int* ptr = (int*)realloc(vect->vec, vect->size + 10);
        if( ptr == NULL )
        {
            return 0; // Error, no hay memoria suficiente
        }
        vect->vec = ptr;
        vect->size = capacity;
    }

    return 1;
}

// Añade un nuevo elemento al final del vector (redimensiona el array si es necesario)
int Add(vector* vect, int value)
{
    if( vect->size == vect->count )
    {
        // Incrementamos la capacidad en 10 (es muy costoso hacer incrementos individuales)

        if( !SetCapacity(vect, vect->size + 10) )
        {
            return 0; // Error, no hay memoria
        }
    }

    vect->vec[vect->count++] = value;
    return 1;
}

Estas utilidades armonizan la forma de utilizar los vectores, ahora los dos se pueden usar exactamente igual, no hay necesidad de duplicar código en ningún sitio.
Ahora tu código se simplifica enormemente:
void llenar(vector *vect)
{
    for(size_t i = 0; i < vect->size; i++)
    {
        Add(vect, rand()%10);
    }
}

void mostrar(vector const* vect)
{
    for(size_t i = 0; i < vect->count; i++)
    {
        printf("%i ",vect->vec[i]);
    }
    putchar('\n');
}

int main(void)
{
    vector original = NewVector();
    vector nuevo    = NewVector();

    SetCapacity(&original, 4);

    srand(time(NULL));
    llenar(&original);

    printf("Vector original:");
    mostrar(&original);

    sacar_repetidos(&original, &nuevo);
    printf("Vector sin repetidos:");
    mostrar(&nuevo);

    printf("Tamaño del nuevo vector: %lu\n", nuevo.count);

    FreeVector(&original);
    FreeVector(&nuevo);

    return 0;
}

Para empezar, te estás ahorrando una función para imprimir el segundo tipo de vector (código duplicado), y aún no hemos empezado a actuar sobre la función importante de tu programa:
void sacar_repetidos(vector const* original, vector * sin_repetidos)
{
    for (size_t i = 0; i < original->count; i++)
    {
        int repetido = 0;
        for( size_t j=0; j<sin_repetidos->count && !repetido; j++)
        {
            repetido = original->vec[i] == sin_repetidos->vec[j];
        }

        if( !repetido )
        {
            Add(sin_repetidos, original->vec[i]);
        }
    }
}

La búsqueda de elementos repetidos no podría ser ahora más simple. Se recorre el array original y, para cada valor, se realiza una búsqueda en el array que no tiene duplicados. Si el número no se encuentra en este segundo array es porque es un número nuevo, lo añadimos a este vector y pasamos al siguiente número.
Puedes ver el código funcionando aquí
No me propuesto corregir tu código porque la implementación es un poco caótica. Hay veces en las que es preferible tirarlo todo y empezar de nuevo, lleva menos trabajo.
Así, por ejemplo, llamas a malloc dentro del bucle:
for (i = 0; i < a->size; i++)
{
  int j = 0;
  while(j <= b->nuevo_size )
  {
    if(b->nuevo_size == 0) //no lo tengo que comprar con nada porque es el primero entonces lo aloco directamente
    {
      b->vec2 = malloc(1*sizeof(int));
      b->vec2[j] = a->vec[i];
      b->nuevo_size = 1; //este es el caso donde me obliga a poner el valor concreto, 1 pero no me deja escribir  b->nuevo_size = b->nuevo_size+  1; y no se por que
    }

Ese código está claramente fuera de lugar. Es una creación incondicional, es decir, lo primero que haces al entrar en ese bucle es hacer una reserva para un primer elemento. Si es incondicional, ¿Por qué no hacer esta reserva fuera del bucle? Así el bucle sería más sencillo de revisar.
Bucles anidados:
while(j <= b->nuevo_size )
{
  // ...

  while (b-> vec2[j] != a->vec[i]  && j <= b->nuevo_size) //mientras el valor de vec2

Se supone que únicamente hay que recorrer el array b una vez por cada valor del array a. No hay necesidad de anidar dos bucles cuya misión, en teoría, es recorrer b.
Otro detalle, este tiene que ver con tu duda, no, el código no tiene por qué entrar en el if:
  while (b-> vec2[j] != a->vec[i]  && j <= b->nuevo_size) //mientras el valor de vec2 sea distinto al vec y sea menos que el tamaño del vec2
  {
    printf(" %i",j); //imprimo para corroborar los valores de i y nuevo_size y veo que son los mismos efectivamente
    printf(" %i ",b-> nuevo_size);
    j++;
    printf(" %i ",a->vec[i]);
    printf("\n");

  }
  if (b-> nuevo_size == j ) //este es el if al que deberia entrar pero no lo hace por mas que veo que alcanza los valores que le estoy pidiendo

Fíjate en las condiciones del while. Tiene lo siguente: j <= b->nuevo_size. Por otro lado, el contenido del while incrementa j. El efecto que se puede conseguir es el siguiente:

*

*j < b->nuevo_size -> Se ejecuta el bucle, se incrementa j

*j == b->nuevo_size -> Se ejecuta el bucle, se incrementa j

*j > b->nuevo_size -> Se abandona el bucle, j > b->nuevo_size, tampoco entra en el if
Todo indica que la condición del while está mal escrita y debería ser así:
while (b-> vec2[j] != a->vec[i]  && j < b->nuevo_size)
//                                    ^ menor que en vez de menor o igual

Ahora bien, al corregir este problema el código entra en un bucle sin fin que termina abruptamente cuando el sistema no te deja reservar más memoria ... problemas derivados de tener un bucle anidado.


text:
Q: How to have multiples scenes with layouts I am not understanding how to get layouts and multiple scenes (i.e. org.andengine.entity.scene.Scene) to work together. The examples I see with layouts work by changing activities & layouts together. As I understand it, having multiple Activities is a bad practice, one should instead have one Activity with multiple scenes, but I don't see how to have a layout with each scene.
So I set use the first layout like so:
@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
        this.setContentView(R.layout.splash);
}

then a few seconds later comes time to display a menu, but I also read the one is not supposed to call setContentView() more than once.
Is it not possible to use layouts AND multiple scenes?

A: I don't know what you mean by "scenes", but having multiple activities is pretty much how all Android apps work. You may want to take a look at Fragments, if you want to have just one activity:
http://developer.android.com/guide/components/fragments.html

A: yes, it is possible to use multiple layouts and multiple scenes in single activity by calling

setContentView(R.layout.your_layout);

where ever you want


text:
Q: Should I create three models or a polymorphic type I have a Laravel 8 application and am wondering how to solve the problem of how to solve a typical polymorphic issue. I have an Employee model. That Employee can be an ExecutiveEmployee or EntryLevelEmployee. There will be methods an ExecutiveEmployee has that an EntryLevelEmployee doesn't have and the inverse is also true.
Using Laravel 8, is it right to create a base Employee model (without a corresponding table?) and then create two models named ExecutiveEmployee and EntryLevelEmployee that inherit from Employee? This would also imply that both employee types will have two different database tables, even though there will be a lot of overlapping data.
Does it make sense to just have one Employee model and create a migration that has the employee type listed in the model? I am assuming that it's ok if an EntryLevelEmployee has some database attributes which are relevant to it that may or may not be relevant to an ExecutiveEmployee type here, or is that an incorrect assumption?
What's the correct way to model this in Laravel 8? I prefer to keep everything in one table because of how similar the models are. I do have to keep in mind that there will be data that one has that the other doesn't. There will be different accessor methods as well.
Is it possible to have everything in one employees table while utilizing multiple models? Meaning, if I create two models named ExecutiveEmployee and EntryLevelEmployee they would both query the underlying table employees?
UPDATE 1
The more I research, the more I think polymorphism is the incorrect approach here and what I might need is Single-Table Inheritance. This package seems to bring the capability to Eloquent. Would there be a good reason to not use this?

A: I would use polymorphic relationships in this case, because you are more flexible and have less coupling.
Using the Single Table Inheritance (STI), you can add type specific columns in the employees table and make them nullable. But think about adding/removing types in the future.
executive_employees
    id - integer
    executive_specific - string

entry_level_employees
    id - integer
    entry_level_specific - string

employees
    id - integer
    name - string
    email - string
    employable_id - integer
    employable_type - string

As for the STI the same would be
employees
    id - integer
    name - string
    email - string
    type - string
    executive_specific - nullable string
    entry_level_specific - nullable string

So STI would be suitable when you don't have type specific columns. But you want to add specific behavior in your code. For example a User type (Admin, Author).
Even so, it's a matter of preferences.

A: It really depends on the state and behavior of your employee object.
Below are few points I will consider to make a decision

*

*If your objects' states/properties are different then definitely you will create different models as your data will be stored in different tables.

*If most states/properties are same and some are different, you can
consider storing all in one table/model and for the difference in
behavior create separate table like Ron Van Der Heijden has
suggested and you can consider query scope with that to make
transaction with database.

And another view will be

*

*How many JOINs you will create if you will create different tables,
will that impact the performance and other stuffs, will it make your
code complex?

*Can you make simpler relations and handle stuffs independently?

*When you are making an API, will your
code make the api overworking? or you need to create too many request
for any operation?

These stuffs will decide how you will make a decision.
Update 1:
Another point I would like to add about the package you are thinking to use, consider using a parent key in table and you can define relationships in a single model.I do not think you need to use a package, you can define it yourself, I guess.

A: I don't understand why you don't create a simple one-to-many relation. Based on the information you provided, the polymorphic relation looks unnecessary. I think the right way is to create employee_roles table and relations. Then you can give different permissions to different employee types. There are several ways to do that. You can create a middleware to create route restrictions. You can check the role before executing a function in the controller, and run only if the employee has permission. You can use if-else in blade not to render the parts that can't be used by auth user etc.

A: If you have different "types" of employees, and each employee type should have different logic then yeah, that sounds like a polymorphic relationship.


text:
Q: Gravity Forms add attachment to user notification I am using the following code from Gravity forms to attach a file to the user's notification:
add_filter( 'gform_notification_55', 'add_attachment_pdf', 10, 3 ); //target form id 2, change to your form id
function add_attachment_pdf( $notification, $form, $entry ) {
    //There is no concept of user notifications anymore, so we will need to target notifications based on other criteria,
    //such as name or subject
    if( $notification['name'] == 'User Notification' ) {
        //get upload root for WordPress
        $upload = wp_upload_dir();
        $upload_path = $upload['basedir'];

        //add file, use full path , example -- $attachment = "C:\\xampp\\htdocs\\wpdev\\wp-content\\uploads\\test.txt"
        $attachment = $upload_path . '/2020-RSPA-POS-Channel-KPI-Study-Update-Post-COVID.pdf';

        GFCommon::log_debug( __METHOD__ . '(): file to be attached: ' . $attachment );

    }
    //return altered notification object
    return $notification;
}

In addition to adding an attachment to form 55, as shown in the example, I need to add a different attachment to a different form. I have changed the form ID to reflect this and copied/pasted the code into the functions file a second time, but the site breaks in doing so. The above works as expected, on it's own. How can I use the filter multiple times?

A: The absolute simplest way (but not the prettiest) would be to duplicate everything and change the function name. Here's an example where I update the function name in both instances to match the form ID:
add_filter( 'gform_notification_55', 'add_attachment_pdf_55', 10, 3 );
function add_attachment_pdf_55( $notification, $form, $entry ) {
    ...
}

add_filter( 'gform_notification_56', 'add_attachment_pdf_56', 10, 3 );
function add_attachment_pdf_56( $notification, $form, $entry ) {
    ...
}


text:
Q: How do you compare carsharing plans to calculate the cheapest? Call hourly rate = HR. Assume that I can guess my monthly usage in hours, which I call $g$. Beware that the fixed fees are presented in different units of time, so first convert everything into months, because it's easier to estimate car usage monthly than yearly. Then Simple's monthly fee $ = 45/12 = \$3.75$.  My problem strategy is to compare 2 plans at a time, by sampling without replacement and ordering, with $\frac{3!}{1!(3- 1)!} = 3$ comparisons in total. In each comparison, I'd determine the breakeven number of hours between the 2 plans, then by comparing it with $g$, I'd instantly know the cheaper plan. Is this the simplest method? How would I execute it?

[Source]
The last row above displays the daily mileage limit, at or below which the HR remains constant and independent of km travelled. Penalties exist for mileage above the limit, which I won't exceed so I ignore them. Autoshare confirms that for any particular car at the same location, Simple's HR (whatever it is) is always exactly $-\$1$ than that for Metro and Metro Plus.
  I omit the row for rates 'per 24hr' because if you need a car for 24 consecutive hours, car rental (eg Budget, Enterprise) is cheaper than car sharing. Anyhow, FYI, for a given car at the same location, Simple's 'per 24hr' rate is always $-\$5$ than Metro's and Metro Plus's.

My first attempt compares Simple and Metro. Call the breakeven number of hours $h$. Then Simple's monthly cost = Metro's monthly cost $\implies (9.25 \text{ to } 13.25)h + 3.75 = (8.25 \text{ to }  12.25)h + 15$.
$1.$ The stated HR are stated as a closed interval, so how do I quantify them?
$2.$ How do I adjust for  the greater mileage offered by Metro Plus?
Update 2015 Jan 6: I show user Ross Millikan's calculations here.
you would have to use the car 135 hours per year to compensate for the added annual fee. - Is this just $\frac{\text{Metro's Annual Fee} - \text{Simple's}}{\text{HR difference between Simple and Metro}} = \frac{\$15 \times 12 - \$45}{$1} = 135$ hours?
The added km on Metro plus come at a price of 120/year - Is this just Metro Plus's Annual Fee $-$ Simple's = $\$(25 - 15) \times 12 = \$120$?

A: You define a usage model, which for your examples must include hours and km per month.  Your model should be a probability distribution of how you will use the cars.  The output will be a probability distribution of costs.  The simple answer is to take the expected value of each distribution and take the least.  Harder is if one service will charge you an enormous amount for going over some number of miles, but you have to sign up with one and only one.  Then you are insuring against wanting that many miles.  Welcome to real life.


text:
Q: custom ListView command set extension I am very new to SPFX and would like to know if you can help me. I have added a new option to the context menu; please see the photo below.
What I need is for when the users click on either of the new menus, it takes them to, for instance, https://google.com or another path.
Can you please let me know where in the code I can achieve this.

A: You have to write your business logic in onExecute method.
For example:
@override
public onExecute(event: IListViewCommandSetExecuteEventParameters): void {
  switch (event.itemId) {
    case 'COMMAND_1':
      window.open('https://google.com','_blank');
      break;
    case 'COMMAND_2':
      window.open('https://google.com','_blank');
      break;
    default:
      throw new Error('Unknown command');
  }
}

Documentation: Build your first ListView Command Set extension


text:
Q: Cual es la direfencia entre request.query_params y self.request.query_params en Python con Django Estoy iniciando con djangorestframework de django-python y tengo el siguiente codigo:
class ProcesoViewSet(ModelPagination, viewsets.ViewSet):

    def list(self, request):
        query = request.query_params
        query1 = self.request.query_params
        log.info(query)
        log.info(query1)

Me gustaría saber cual es la diferencia, hice log a los dos valores este es el resultado (es lo mismo)
<QueryDict: {'page': ['1'], 'all': ['false']}>
<QueryDict: {'page': ['1'], 'all': ['false']}>

Pero me gustaría saber existe ventajas y desventajas de usar una o la otra. Gracias.

A: Cuando se solicita una página en Django, se crea un objeto HttpRequest que contiene información sobre la solicitud, es decir, sus atributos y métodos.
En tu ejemplo, este objeto se encuentra en la instancia de la clase ProcesoViewSet y tienes acceso a él desde la instancia usando self.request.
En def list(self, request) existe un parámetro que se llama request, pero es solo una etiqueta. Casualmente se llama request y causalmente contiene el contenido del objeto self.request. Pero solo es casualidad. Su nombre podría ser req o solicitud o cualquier otro y su función sería la misma.
Ahora bien, ambos objetos pueden tener el mismo contenido, pero no necesariamente son el mismo objeto.
Para verificar si dos objetos tienen el mismo contenido, usa el operador lógico ==.
query == query1

Para verificar si dos variables se refieren al mismo objeto, usa el operador is:
query is query1