text:
Q: Displaying the error in production mode with log number in laravel I have an application built in laravel 5.8 which is in production mode. As the site is live I don't want to display any errors to our users. But If some error occurs then I want the log number or any reference that indicates what error was thrown at that particular time.
So I wanted to know if there is any way to display "Oops something went wrong ref#123456" to our users. So that they can send us a screenshot or reference number and we can track what actually happend by checking our log file.
Thanks in advance. Happy coding.

A: I thing that you can do it saving the logs in database and render its id.
You can do it in App\Exceptions\Handler:
https://laravel.com/docs/5.8/errors
For example:
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        // Create log in db
        $log = Log::create([
            'message' => $exception->getMessage(),
            'code' => $exception->getCode(),
            'line' => $exception->getLine(),
        ]);

        // Print log id in logs
        logger("LogId {$log->id}");

        //Return view error with log id
        return return response()->view('errors', ['logId' => $log->id]);
    }

A: maybe you want something more professional than logging the exception, and laravel have a great package for it named telescope you got all your exceptions and queries or events redis and ... so many. you can authorize the users that only admins can access telescope information. and because its a lot of info probably you want prune the records with a seceule:
$schedule->command('telescope:prune --hours=48')->daily();

all of this you can find it in docs: https://laravel.com/docs/telescope

A: It should be as simple as using uniqueid() function to create an id for an exception, and returning a view in the render part of your app.
public function render($request, Exception $exception)
{
    $errorCode = uniqid('error_');

    Log::error("$errorCode", [
        //... The log information here
    ]);

    return view('welcome', compact('errorCode'));
}

As an example above I am using the default welcome.blade.php page, and then showing the content below:

Error occurred #error_5ec385d7c4d25

It means you can actually search your logs for this error code to know what went wrong.


text:
Q: Convert NSTask "/bin/sh -c" command into proper pipeline code Can someone help me convert the following code into code that instead has two NSTasks for "cat" and "grep", showing how the two can be connected together with pipes? I suppose I would prefer the latter approach, since then I no longer have to worry about quoting and stuff.
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-c",
             @"cat /usr/share/dict/words | grep -i ham", nil];
[task setArguments: arguments];
[task launch];

Update: Note that cat and grep are here just meant as (lousy) example. I still want to do this for commands that make more sense.

A: Use a instance of NSTask for each program and connect their standard inputs/outputs with NSPipe:
NSPipe *pipe = [[NSPipe alloc] init];
NSPipe *resultPipe = [[NSPipe alloc] init];

NSTask *task1 = [[NSTask alloc] init];
[task1 setLaunchPath: @"/bin/cat"];
[task1 setStandardOutput: pipe];
[task1 launch];

NSTask *task2 = [[NSTask alloc] init];
[task2 setLaunchPath: @"/bin/grep"];
[task2 setStandardInput: pipe];
[task2 setStandardOutput: resultPipe];
[task2 launch];

NSData *result = [[resultPipe fileHandleForReading] readDataToEndOfFile];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically creating new screen in react-native I am trying to create web browser using react-native and react-native-web-view.
One of the crucial function in browser is tab feature, in which users create multiple tabs for different urls and switch between them.
The logic would be to push new screen to the navigation(without statically predefining) every time a user creates a new tab. However, navigation library like react-navigation don't allow that. You have to predefine the screens before loading the corresponding screen.
I want something in the line of...
const pressNewTab=()=>{
   NavigationActions.navigate({ routeName: `${newRouteName}`, params: { id, ...otherParams } }),
}

Is there any way to achieve the feature?

A: React Navigation 5 allows you to dynamically add/remove screens: https://next.reactnavigation.org
But for your case, looks like a good way is to use a Stack navigator:

*

*add new screens using doing navigation.push with different params for each route: (e.g. navigation.push('Tab', { url: '...' })

*then render a custom header which shows the list of tabs

This should achieve the same behaviour as a tabbed mobile browser.

A: I think you can probably achieve this by:
let's Imagine if the user has created an array of data for example

notes=['Note1', 'Note2', 'Note3', 'Note4']

class TabScreen extends Component {
   Tabs = navigation => {
    let notes=['Note1', 'Note2', 'Note3', 'Note4']
    notes = notes.reduce((val, tab) => {
      val[tab] = {
        screen: tab
      }
      return val
    }, {})

    const Tabs = createTabNavigator({
        ...notes
      },
      {
        ...TabNavigator.Presets.AndroidTopTabs,
        lazyLoad: false,
        tabBarOptions: {
          scrollEnabled: true,
          style: {
            backgroundColor: Colors.snow,
            height: Header.HEIGHT - 15
          },
          tabStyle: {
            width: 100
          },
          indicatorStyle: {
            width: 0
          }
        }
      }
    )return <Tabs />
  }

render () {
    const { navigation } = this.props
    return (
      <View style={styles.container}>
          {this.Tabs(navigation)}
      </View>
    )
  }
}


text:
Q: Remove file from github I need your help.
I just remove a file (Python 1D MEM.ipynb) from local (My PC) since my written code was messy.
Then I downloaded that file (Python 1D MEM.ipynb) from my Github to the PC as my backup.
the problem is the oversize file (Automated 1D MEM.ipynb) of my previous uploaded. So I got this message and being unable to upload a new one (Python 1D MEM.ipynb).
PS. Python 1D MEM.ipynb and Automated 1D MEM.ipynb are the same file, just renamed.
And I prefer to use a new one (Python 1D MEM.ipynb).
How do I solve this. I just want to remove the old one (Automated 1D MEM.ipynb) on remote.
and upload a new one (Python 1D MEM.ipynb) instead.
(datascience) D:\Github\1D MEM>git push -f origin master
warning: redirecting to https://github.com/phumikrai/1D-MEM.git/
Enumerating objects: 102, done.
Counting objects: 100% (101/101), done.
Delta compression using up to 8 threads
Compressing objects: 100% (96/96), done.
Writing objects: 100% (96/96), 56.96 MiB | 1.62 MiB/s, done.
Total 96 (delta 46), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (46/46), completed with 1 local object.
remote: warning: File Automated 1D MEM.ipynb is 82.49 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: df632e0207decf41410cbccae69ce3b6826362c5a1b26e0a195fa50d81b3ebed
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File Python 1D MEM.ipynb is 100.75 MB; this exceeds GitHub's file size limit of 100.00 MB
To http://github.com/phumikrai/1D-MEM.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'http://github.com/phumikrai/1D-MEM.git'

A: IPython notebook files are somewhat akin to word documents: they get very large, and aren't actually able to be properly line-diffed due to being largely binary (read: not human-readable). Instead, I recommend backing up these notebooks in a cloud storage service like Google Drive and OneDrive. Those services also have versioning support that can be set up.
Clearly this is a very large python notebook if it has 100MB of information. Git isn't designed to handle these types of files.


text:
Q: when i archive with xcode6 ,failed to locate or generate matching signing assets questios follows:
No matching provisioning profiles found for "application/lottery.app"
none of the valid provisioning profiles allowed the specified entitlements:application-identifier,beta-reports-active,keychain-acccess-groups.
come to save me,or i will be over.

A: Similar problem answer at:See the SO answer
On a side note:
You might want to install IPhone Config Utility
If you want to understand what all the terms like Provisioning, Developer Certificate and Key mean you might want to read this tutorial. Under the hood its just plain Public-Private key pair based Asymmetric Encryption Operations.


text:
Q: ABRecordCopyValue only returning Facebook email for Contact and ignoring others I am trying to compare the emails of a selected phone contact to the emails of registered users in my app to see if they are registered.
It should be simple enough. Get the recordRef, copy the email multiValue, then compare:
-(void) checkForUser:(ABRecordRef) person {

    ABMultiValueRef contactEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
    NSLog(@"emails are %@", contactEmails); // seeing error in log

    ...
    // check the emails against registered users.

This works great most of the time. Problem comes with unified contacts. My contact for example is a unified record with my Facebook, home, work emails all in one contact. When I run checkUser: with that ABRecordRef it is ONLY showing my Facebook email even though there are 4 others.
I am thinking this is a bug. Am I missing something about unified cards?

A: This is what I did, you can see if your code is similar - if so no more info to provide you:
ABMutableMultiValueRef multiValue = ABRecordCopyValue(person, kABPersonEmailProperty);
//CFShow(multiValue);
if(multiValue) {
    for(CFIndex j=0; j<ABMultiValueGetCount(multiValue); ++j) {
        //CFShow(ABMultiValueCopyLabelAtIndex(multiValue, j) );
        CFStringRef label = ABMultiValueCopyLabelAtIndex(multiValue, j);
        if(![emailKey isEqualToString:(__bridge NSString *)label]) {
            CFRelease(label);
            continue;
        }
        CFRelease(label);

        CFStringRef string = ABMultiValueCopyValueAtIndex(multiValue, j);
        NSString *finalStr = CFBridgingRelease(string);

        NSArray *array = [finalStr componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        if([array count] == 3)  finalStr = (NSString *)[array objectAtIndex:1];

        [data replaceObjectAtIndex:emailAddress withObject:finalStr];
        break;
    }
    CFRelease(multiValue);
}


text:
Q: something that looks like a Renewal Process, but it is not Assume $X_{n}$ is an i.i.d (independent, identical distribution) sequence of random variables with the distribution function F(x) and non-negative expected value, $EX_{n}=\mu>0$ . Let $Y_n=0,Y_n=\sum_{k=1}^{n}X_k, n>=1; N(t)=sup[n:Y_n<=t]$. Find the distribution of N(t) and EN(t).
Now if $X_{n}$s were non-negative, $N_t$ would be a renewal process. but, here, the only info we have (that I don't know where to use it) is that $EX_{n}=\mu>0$.
so my first question is
1-N(t) is a counting process anyway, regardless of $X_n$ being positive or negative, right? what is its distribution function?
2-I have read this almost related answer: https://math.stackexchange.com/questions/1654305/renewal-process-and-renewal-function
but as I said I'm not sure if it is a renewal process at all. If yes, I am not sure if the lower limit of the integral $(F \star F)(t)=\int_0^t F(t-u)F(du)$ should stay $0$ or it should be - infinity?
3- Is the following way to compute $EN(t)=m_t$ correct?
$m_t=\sum_{n=0}^{\inf}nP(N(T)=n)=\sum_{n=1}^{\inf}P(N(T)>=n)=\sum_{n=1}^{\inf}P(Y_n<=t)=\sum_{n=1}^{\inf}F_n(t)$ where $F_n(t)$ is the dirstibution function of $Y_n$


text:
Q: ERROR: Conditional jump or move depends on uninitialised value(s) ERROR: Conditional jump or move depends on uninitialised value(s)
Hi I would like to know if someone would have the solution to solve my problem I do not understand why it is said that tab [c] is not initialized it puts me
#include <stdio.h>
#include <stdlib.h>
void maloc(int x)
{
    char* tab = 0;
    int c = 0;
    int i = 1 ;
    int swap;
    if(x > 0)
    {
        tab = malloc((x+1) * sizeof(char)); // On alloue de la mémoire pour le tableau
        if(tab == 0) // On vérifie si l'allocation a marché ou non
        {
            exit(0); // On arrête tout
        }
        else
        {
            while (tab[c] != '/0' )
            {
                tab[c] = i + '0';
                i++;
                c++;
            }
            c = 0;
        }
    }
    free(tab);// On libère la mémoire allouée avec malloc, on n'en a plus besoin
}

int main()
{
    maloc(4);
    return 0;
}

A:
I do not understand why it is said that tab [c] is not initialized

malloc() does not initialize the memory it provides, so immediately after you perform ...

        tab = malloc((x+1) * sizeof(char));

... there is no value of c for which tab[c] has been initialized.  In particular, the value of c at that point is 0, and tab[0] is not initialized.
The calloc() function, on the other hand, does provide initialized (to all-bytes zero) allocated memory, but if you used that (and corrected the typo, '/0' to '\0') then you should not expect any iterations of your while loop to be performed, as the condition would be false the first time it was tested.
I think you're trying to be too clever.  It looks like this would do what you are trying to do with the while loop, more clearly and easily:
            for (int i = 0; i < x; i++) {
                tab[i] = i + '1';
            }

If you really want to allocate that extra byte and initialize it to 0, then you could add ...
            tab[x] = 0;

... afterward.


text:
Q: IF(x="y";"Yes";"No") . How to expand with multiple conditions? I have a formula =IF(Functie="Medewerker Verhuur";"Yes";"No")
This works, but now i would like to add the option Medewerker Klantenpunt too.
So, if Functie is Medewerker Verhuur OR Medewerker Klantenpunt, than yes, ELSE No.
How do i do this? I cannot get it to work.

A: Try something like this:
=IF(OR(Functie="Medewerker Verhuur";Functie="Medewerker Klantenpunt");"Yes";"No")

It uses OR operator/function which is described here.


text:
Q: Combobox SelectedItem does not work I have the code below
FooCB.DisplayMember = "FooNome";
FooCB.ValueMember = "Foo";
FooCB.DataSource = FooRepository.Instance.All();
FooCB.DataBindings.Add("SelectedItem", Bar, "Foo");

but when I display the form the SelectedItem is always the first.
What am I doing wrong?

A: I have been struggling a little with the behaviour of Winforms comboboxes and databinding recently and these are my observations (.Net4) when binding the ComboBox.DataSource to a list of items and also binding an object property to ComboBox.SelectedItem.

*

*When binding a list of objects (in your case List<Foo>) to ComboBox.DataSource, the first object in the list is always shown in the combobox.

*If you bind an object property to ComboBox.SelectedItem (in your case Bar.Foo) and that object property matches one of the combobox list objects then that object is displayed in the combobox. If the object property is null (Bar.Foo == null) or the object property is not in the combobox list then the first object is shown in the combobox.

*Setting ComboBox.SelectedItem = null or ComboBox.SelectedIndex = -1 clears the displayed item on the combobox even though this seems to warn against it. And will set your bound object property to null.

*If a user clears the combobox selection when using ComboBox.DropDownStyle == DropDown (with backspace) then the bound object property is set to null.

*If you have implemented INotifyPropertyChanged on the object whose property is bound to Combobox.SelectedItem (Bar.Foo) and you programatically set the bound property to a value and that value appears in the combobox list then the changed value will be displayed. If you set the property to null or a value not in the list then the combobox displayed value will not change.
So what can you do about it? The only real issue I have is having no value displayed when my bound property is null so I have just been explicitly setting Combobox.SelectedItem = null as in point #3. You may be able to extend ComboBox and override the default behaviour but so far I have been content with an extra line of code here and there combined with using default values on non-nullable properties.

A: Probably you are missing some decleration. If you created the Combobox from the Tool Box, -I had the similar problem- you might want to add name of the Combobox's Name as a tag on XAML.
Other than that, if you created it dynamically by code, check if you are missing any decleration for class.

A: I can't tell from the OP's code whether I'm answering their question, but maybe this will help somebody reading this question.  The ComboBox has four ways to set the current value:
SelectedIndex
SelectedItem
SelectedText
SelectedValue

You need to be consistent about what you're setting (and about which event handler you're using).  You'll get an error if you set SelectedIndex to something dumb (less than -1 or longer than the list).  However, you don't get errors setting the other three to something that doesn't exist for that type of selection.
Suppose you use a Dictionary (that's pseudo code) as a binding source and set DisplayMember = "Value" and ValueMember = "Key", the mapping would look like:
SelectedIndex - -1 to index of last item
SelectedItem - KeyValuePair<Key, Value>
SelectedText - Dictionary value
SelectedValue - Dictionary key

Supplying either value or key to SelectedItem will not generate an error, it will simply act like the OP has described.  And that's why I thought this answer might help somebody.
I might also note that, if you're swapping out the contents of the ComboBox, it's not always safe to use SelectedIndex.  Suppose the same basic kind of data is in the ComboBox, but selections are limited in some cases compared to others. Using SelectedIndex to persist a previous selection that was still valid in the new list of options is only going work if that previous selection held the exact same place in the list.  You'd almost think this was the voice of very, very recent experience speaking...


text:
Q: Add year of creation in the copyright header of each file with reuse A git repository has many files and each file should get a SPDX license header.
The license header should be created by reuse and use the year of creation as year in the copyright.
example of what I want to get:

$> head -v -n1 *.py       # Prints first line of each file

==> made_on_2006-01-01.py  <==
# SPDX-FileCopyrightText: 2006 Bob Doe <bob@example.com>

==> made_on_2012-02-02.py  <==
# SPDX-FileCopyrightText: 2012 Alice Doe <alice@example.com>

==> made_on_2020-03-03.py  <==
# SPDX-FileCopyrightText: 2020 Bob Doe <bob@example.com>

How can I create these headers with reuse, git and standard command line tools on Linux?
I think this is useful for projects with a single coder where you want to note the copyright with the first day of file creation.


text:
Q: Time complexity of nested while with changing condition I'm trying to solve the complexity of this loop
for(int i= 0; i < n; i++) {
 c = i;
 while(c > 1){
  O(1);
  c = c / 2;
 }
}

as the while condition changes in every loop I don't know how to calculate that strange series.
I mean, if the loop where
for(int i= 0; i < n; i++) {
 c = n;
 while(c > 1){
  O(1);
  c = c / 2;
 }
}

I know the while has a complexity of O(logn) and it repeats itself n times, so the complexity would be O(nlogn).
The problem I have with previous loop is "c=i". As c=i, first time (c=0) the loop would reproduce 0 times, when c=1 it would reproduce 0 times again, when c=2 it would reproduce 1 time, then the series would follow and it is 0, 0, 1, 2, 2, 3, 3... (while reproductions each time of for loop)
O(logn) would not repeat itself n times, would repeat a number of times I can't come up with, so I don't know how to solve it.

A: This need a bit of math involved.Given that log is well defined for a and b:
log(a) + log(b) = log(ab)

Here you have
log(1) + log(2) +....+ log(n) = log(1*....*n) = log(n!)

There is a mathematical approximation for log(n!), namely
 log(n!) ~ nlog(n) - n + 1

which reveal O(log(n!)= O(nlog(n))


text:
Q: How do I fix randomly moved chunks after a crash? I was stupid and didn't keep a backup of my Minecraft server.  Now, it crashed, biomes changed, chunks were moved around, part of my city of gone, an underground chunk was moved aboveground, is there ANY way I can fix this?
I.E. easily move chunks and change biomes.

A: For anyone still looking for a fix:

*

*Download and open Mcedit

*Open your world using this program.

*Do Ctrl+I

*Click fix regions.

A: They were moved because the map files got corrupt so it reads chunks in an out of place order.
It's like 1 2 3 4 5 6 7 8 9 would turn into 1 0 4 6 7 8 9 0 0, where 0 would be unreadable thus deleted.

Picking a known map editor should allow you to move chunks, they include terrain/forest generators.
And set up an automated back-up solution...

A: *

*Backup your world by copying the folder (either in operating system users folder or wherever you keep your minecraft server executables).

*Close Minecraft single player game or server to avoid world corruption.

*Download and open MCedit 1.3 (at the time of this writing, MCedit 2.0 alpha is not in good shape).

*Open your world in MCedit.

*Select problem chunks and DELETE them. They'll respawn in their original state when you log onto the world again.

*Once you're sure you've deleted those problem chunks (and only those), save & exit.

*Start your server / single player game up again. You should be ready to roll.


text:
Q: OpenStack Nova fails to connect to libvirt (not socket issue!) We're trying to deploy OpenStack on hardened Debian-based Linux distro via Kolla-ansible and we seem to be almost done but facing the issue with the nova_compute container which complaints:
2021-09-12 08:56:34.365 7 INFO nova.virt.libvirt.driver [-] Connection event '0' reason.
 'Failed to connect to libvirt: Unable to query peer security context: No data available

and restarts permanently.
Here are relevant config snippets:
(venv) root@server11:~# grep nova /etc/kolla/globals.yml
nova_backend_ceph                  : "yes"
nova_compute_virt_type             : "qemu"
(venv) root@server11:~# cat /etc/kolla/config/nova/nova-compute.conf
[libvirt]
virt_type=qemu
cpu_mode = none
(venv) root@server11:~#

Tried to figure out the root cause myself, read the docs, googled but to no avail, so any suggestions on how to fix the issue will be highly appreciated.

A: This error message means that the getpeercon() method failed. This method is only run it libvirt is built with SELinux support.  The "No data available" return value suggests perhaps SELinux is turned off, but that should already have been caught by the "ENOSYS" / "NOPROTOOPT" checks.


text:
Q: Make particular View visible when comment section start In this code there is description part, comments section and one comment TextInput.
 So I want to make TextInput View visible when comment section View start that is when user will scroll to comment section and TextInput View will be hidden when when the user is on description part.
For this i think we need to find the height of description View and if it crosses to that height then the comment TextInput View will be visible. but i am not sure with it.
suggest if anyone know the solution.
renderCommentInput(){
 return(
  <View>
   <TextInput/>
  </View>
 );
}

render() {
 return(
 <Container>
   <ScrollView>
     <View>
      <Text>{this.state.description}</Text>
     </View>
     <View>
     // The code to print comments in map
     </View>
    </ScrollView>
    {this.renderCommentInput()}
  </Container>
 );
}


text:
Q: JBPM rest calls with JSON We want to start a process in JBPM6 using the rest API. We need to pass an object as a process variable.
We know how to do it JAXB and the execute call. But we want to do it with JSON and /runtime/{deploymentId}/process/{processDefId}/start
Is it possible? we try and have no success.

A: I am not sure whether my answer exactly addresses the question. But for someones use in future I place couple of lines here.
If you want to set a process variable when starting a process using the RESTful API, you can do it like this.
If your variable name is myVar just add the value as a URL parameter by appending the phrase "map_" to the parameter name. It means the parameter name should now be map_myVar. For an example see below request.
http://<host>:<port>/jbpm-console/rest/runtime/{deploymentId}/process/{processDefId}/start?map_myVar=myValue

You can confirm whether the value is set by writing below code in a script task.
Object var = kcontext.getVariable("myVar");
System.out.println("myVar : " + var);

See the 17.1.1.3. Map query parameters section of JBPM6 documentation.

A: After talking to the dev that is responsible for the REST API. I was able to confirm how it works.
The
/runtime/{deploymentId}/process/{processDefId}/start
Is a POST request where all the contents in the payload are ignored. The variables are written as key=value in the GET string.
With deployment id: com.web:work:1.0
With processDefId: work.worload
2 variables: var1 and var2
For example:
/runtime/com.web:work:1.0/process/work.worload/start?var1=a&var2=b
I'm still after trying to understand how to define objects with the remote API.
Meanwhile, I also confirmed that it is impossible to define objects using this way. The only way to define objects is only by using the JaxB. This uses the "/execute" path


text:
Q: Sharepoint 2016 REST API - get list ID & file ID from direct file link I have the full SharePoint URL for a file, like: https://my-sharepoint-host.net/subsite/library/LOOONG folder name that exceeds the configured maxUrlLength value/fileName.txt
I need to obtain some details about that file: the listId and the fileID, so that I can then reach it with a link like https://my-sharepoint-host.net/_api/Web/Lists(guid'xxxxx-xx-xxxx')/Items(xx)/File .
But the original URL is too long, and I cannot used it in a /_api/web/GetFileByServerRelativeUrl(... HTTP Request.
If I try this, I get the message The length of the URL for this request exceeds the configured maxUrlLength value. from SharePoint.
What options do I have ?
What URL can I call to get those id field for the file ?
Thank you.

A: Have  you tried reading the file from PowerShell?  That should at least get you the GUID for the file:
Requires SharePoint PnP
$site_url = "https://my-sharepoint-host.net/subsite/library/"
Connect-PnPOnline  -Url $site_url -UseWebLogin
$Items = (Get-PnPListItem -List $list_name  -PageSize 2500).FieldValues
foreach($Item in $Items)
{
  # echo out the file meta data, look for the document GUID
  $Item.FileLeafRef
}


text:
Q: Scala select an element from a list based on that element's sublist properties Very similar to this question, but a little different.
I have a List[Family], and each Family keeps a List[People] and I want to select the first Family if that Family has a Person by the name I'm looking for
case class Person(name: String, age: Int)
case class Family(surname: String, members: List[Person])

def findFamilyByPerson(families:List[Family], personName:String): Family = ???

val per1 = Person("Tina", 4)
val per2 = Person("Mike", 15)
val per3 = Person("Mary", 77)
val per4 = Person("John",34)
val fam1 = Family("Hetfield", List(per1, per2))
val fam2 = Family("McCoy", List(per3, per4))

println(findFamilyByPerson(List(fam1, fam2), "Mary").surname) // should print "McCoy"

I tried defining findFamilyByPerson as:
def findFamilyByPerson(families:List[Family], personName:String): Family = {
     families.flatMap(_.members).find(_.name == personName)
 }

but this returns an Option[Person], when what I want is that Person's Family
I'm guessing it has something to do with flatMap and Find, but just not quite sure how to work that out.

A: def findFamilyByPerson(families:List[Family], personName:String): Option[Family] = {
     families.find(_.members.exists(_.name == personName))
}


text:
Q: noob struggle with jekyll syntax highlighting: HTML is rendered but the stylesheet seems to be missing I'm getting started with Jekyll. I carefully followed the step-by-step tutorial https://jekyllrb.com/docs/step-by-step/01-setup/ like a good person, and everything is brilliant except that syntax highlighting is not working out of the box like the advertisement seems to imply. I've read jekyll syntax highlighter not working but the answer didn't do it for me.
Where my markdown says, e.g.,
```php

namespace Foo;
use My\Thing;

$thing = new Thing();

```

the output is

namespace Foo;
            use My\Thing;
            $thing = new Thing();

but I'm not seeing any pretty colors. Obviously I am missing the CSS resource that defines highlighter-rouge and all that good stuff, but for all my searching I haven't been able to figure out where to get it or what I might be doing wrong.
I have tried multiple permutations of _config.yml with no luck, but I shouldn't need any special settings there because the default is what I want.
Suggestions?
Thanks.

A: You can find custom syntax highlighting libraries on GitHub and elsewhere, but you may want to start with https://prismjs.com/


text:
Q: Numbers in three different formats I am working with a dataset; below you can see a small example.
import pandas as pd
import numpy as np

data = {
         'id':['9.','09', 9],
        }
df = pd.DataFrame(data, columns = [
                                      'id',])

df['id'] = df['id'].replace(".","")

df

In this data set, one number is written in three ways e.g '9.','09', 9
Now I want to have all of these numbers written in the same way e.g 9, without . or 0
I tried with this line of code but it is not working
df['id'] = df['id'].replace(".","")

So can anybody help me how to solve this problem?

A: You could turn them all into doubles and then into integers
df['id'].astype('double').astype(int)

But this can be a problem for large numbers that exceed the 53 bit significand of the double. If the errant period is always at the end of the string, you could do
df['id'].astype(str).str.strip('.').astype(int)

or even a regex that strips the dot plus anything else to its right.

A: try this:
pd.to_numeric(df['id'])

0    9.0
1    9.0
2    9.0
Name: id, dtype: float64

to int:
pd.to_numeric(df['id']).astype(int)

0    9
1    9
2    9
Name: id, dtype: int64


text:
Q: How to delete a directory I (accidentally) named after an argument I have been playing around with submodules from git and installed my first one in the wrong directory.  Fixed easily enough, but when trying to delete recursively, I put the arguments/files in the wrong order and now I have a directory named --force.
I have tried various commands to remove it, among them -rf (Yes, I know the dangers of it) but I can't seem to get rid of this directory.  Instead, bash thinks that I'm calling an argument and does nothing.
I remember having this problem before, and my teacher told me to back out of the directory and delete it from a directory above, but I have also tried that to no avail. Again, bash thinks I'm referring to an argument.
I seem to have gotten myself in quite a pickle. I know the solution is super simple but I can't seem to figure it out for myself. Any suggestions?

A: You can try a
git rm -r -- --force

(instead of just rm)
That will not only remove it from the working tree, it will also removes it from the git index.
If that folder wasn't added to the index, then rm -rf -- --force is enough)
See "Deleting a badly named git branch" for the explanation  of the double hyphen syntax: it separates the command from the file arguments.


text:
Q: JS using onclick event on li to display block HTML:

Menu

item 1

item 2

item 3

Css:
#dropdown ul{
 display: block;
}
#dropdown ul li {
     display: block;
     background-color: #558c89;
     color: #ffffff;
}
#dropdown ul li ul {
     display: none;
}
#dropdown ul li:hover > ul { /*this is what the onclick event should do*/
     display: block;
}

The onclick should start the function "dropdown()" which needs to: "display: block;" on #dropdown ul li

A: You're missing the list ID and you're calling the selector on the console (when you want to be selecting on the document).

Menu

item 1

item 2

item 3

JSFiddle: http://jsfiddle.net/tmaB9/

A: Try:

This is important, so your function knows which element you clicked on. Then...
function dropDown(li) {
    var submenu = li.getElementsByTagName('ul')[0];
    if( submenu) {
        submenu.style.display = submenu.style.display == "block" ? "" : "block";
    }
}

This will toggle the visibility of the submenu :)

A: here is a quick example of what i think you want (provided you can use JQuery):
    $(document).ready(function () {
        $('#dropdown ul li').on('click', function dropdown() {
            //console.getElementById("").style.display = "block";
        });
    });

menu 1

menu 2

menu 3

menu 4


text:
Q: Google Maps: get lat/lng from geocoded postcode I am currently plotting multiple points on a map, using addresses from an object. The program loops over the object, geocodes the address, and plots a marker for each location.
The problem I am having is when a user clicks on a place in a list, the map is to pan to that location. The API has a panTo() function that accepts lat, lng values, but the results, i.e. results[0].geometry.location, from the geocode function are not available outside of it.
Question
How do I somehow retrieve the lat, lng from the results, maybe append them to the existing data object, and use them outside the function, so I am able to use them in the panTo() function?
[The lat/lng values are output in html data attributes]
Click handler
$('.place').on('click', function() {
    $this = $(this);
    lat = $this.data('lat');
    lng = $this.data('lng');

    map.panTo(new google.maps.LatLng(lat, lng));
});

Data
var locations = [
    {
      id: 'place1',
      postcode: 'B1 1AA'
    },
    {
     id: 'place2',
      postcode: 'CB9 8PU'
    }
];

Code
for (i = 0; i < locations.length; i++) {

  geocoder.geocode({'address': locations[i].postcode}, function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {

          marker = new google.maps.Marker({
              position: results[0].geometry.location,
              map: map
          });

      } else {
          console.log('Geocode was not successful ' + status);
      }

  }); // end geocode

    $(places).append(
        '
'+
            '
'+
                '
'+locations[i].name+'
'+
                '
'+locations[i].territory+'
'+
            '
'+
        '
'
    );

} // end for

A: Give this a go. The IIFE is there to enclose the index so you don't keep hitting the last index of the locations array due to the asynchronous nature of geocode.
  for (i = 0, l = locations.length; i < l; i++) {

    (function(i) { // index passed in as parameter

      geocoder.geocode({ address: locations[i].postcode }, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

          marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map
          });

          $('#places').append(
            '
' +
            '
' +
            '
' + locations[i].name + '
' +
            '
' + locations[i].territory + '
'+
            '
' +
            '
'
          );

        } else {
            console.log('Geocode was not successful ' + status);
        }

      });

    }(i)); // index passed in to IIFE

  }


text:
Q: 2D Bounding box collission i'm having some problems with collission in a small 2D game i'm writing. I'm currently working on a function that i want to find if the player character collides with a block, and which side of the block he collided with.
Currently i have something like (psuedo-code):
if(PLAYER_BOX IS WITHIN THE BLOCKS Y_RANGE)
{
    if(PLAYER_BOX_RIGHT_SIDE >= BLOCK_LEFT_SIDE && PLAYER_BOX_RIGHT_SIDE <= BLOCK_RIGHT_SIDE)
    {
        return LEFT;
    }
    else if(PLAYER_LEFT_SIDE <= BLOCK_RIGHT_SIDE && PLAYER_LEFT_SIDE >= BLOCK_LEFT_SIDE)
    {
        return RIGHT;
    }
}
else if(PLAYER_BOX IS WITHIN BLOCK X_RANGE)
{
    if(PLAYER_BOTTOM_SIDE >= BLOCK_TOP_SIDE && PLAYER_BOTTOM_SIDE <= BLOCK_BOTTOM_SIDE)
    {
        return ABOVE;
    }
    else if(PLAYER_TOP_SIDE <= BLOCK_BOTTOM_SIDE && PLAYER_TOP_SIDE >= BLOCK_TOP_SIDE)
    {
        return BELOW;
    }
 }

Do i have some logic error here? Or have i simply wrote something wrong in my code?
ABOVE collision works, but it doesn't recognize sideways collission when it should, and sometimes it does when it should'nt.
The game is a SuperMario clone, so it's a sidescroller 2D platformer.

A: I'm guessing the issue is direction.
What you really want to do is to take into account the "player" direction first and then do your checks.
If you don't know what direction the player is moving in you could get a number for false hits depending on how "fast" your sprites are moving.
For example if you have movement directions (up down left right) then your code might look like this:
select movedir
(
   case up:
     //check if hitting bottom of box
     break;
   case down:
     //check if hitting top of box

    etc

}

A: You might want to consider revising your calculations by using the movement delta.
Something like this (also pseudo):

// assuming player graphics are centered
player_right = player.x + player.width / 2;
player_left = player.x - player.width / 2;

player_top = player.y - player.height / 2;
player_bottom = player.y + player.height / 2;

// assuming block graphics are centered as well
block_right = box.x + box.width / 2;
...

// determine initial orientation
if (player_right  block_right) orientationX = 'right';

if (player_top  block_top) orientationY = 'top';

// calculate movement delta
delta.x = player.x * force.x - player.x;
delta.y = player.y * force.y - player.y;

// define a rect containing where your player WAS before moving, and where he WILL BE after moving
movementRect = new Rect(player_left, player_top, delta.x + player.width / 2, delta.y + player.height / 2);

// make sure you rect is using all positive values
normalize(movementRect);

if (movementRect.contains(new Point(block_top, block_left)) || movementRect.contains(new Point(block_right, block_bottom))) {

    // there was a collision, move the player back to the point of collision
    if (orientationX == 'left') player.x = block_right - player.width / 2;
    else if (orientationX == 'right') player.x = block_left + player.width / 2;

    if (orientationY == 'top') player.y = block_top - player.height / 2;
    else if (orientationY == 'bottom') player.y = block_bottom + player.height / 2;

    // you could also do some calculation here to see exactly how far the movementRect goes past the given block, and then use that to apply restitution (bounce back)

} else {

    // no collision, move the player
    player.x += delta.x;
    player.y += delta.y;

}

This approach is going to give you a lot better results if your player ever moves extremely fast, since you're essentially calculating if the player WILL collide, rather than if they DID collide.


text:
Q: SyntaxError: invalid syntax в Питоне 3 Написал программу, которая загадывает число от 1 до введенного числа, и игроку надо его угадать, но на проверке введенного числа выдает SyntaxError. Что я делаю не так?
from random import randint

top = int(input('Input a highest possible number. '))
rand_number = randint(1, top)
attempt = 0
while 1 == 1:
    guess = (input('Input your guess. ')
    if 1 > guess or guess > top: # Если guess вне [1, top], отсюда начинаются ошибки.
        print('Are you giving up? Y/N ')
        answer = input()
        if answer in ['N', 'n', 'No', 'no', 'NO']:
            print("OK, we are back to the game!")
            continue
        else:
            print('GAME OVER')
            break

A: guess = (input('Input your guess. ')
не хватает скобки

A: from random import randint

top = int(input('Input a highest possible number: '))
rand_number = randint(1, top)
attempt = 0

while True:
    guess = int(input('Input your guess: '))
    if guess not in range(1, top):
        answer = input('Are you giving up? Y/N ')
        if answer.lower() in ('n', 'no'):
            print("OK, we are back to the game!")
            continue
        elif answer.lower() in ('y', 'yes'):
            print('GAME OVER')
            break


text:
Q: Do VSS 6 archives open on VSS 2005? We have archive of VSS 6 but donot have VSS client.
We have client for VSS 2005. Is it possible to access the VSS archive of v6 from VSS 2005 client?

A: The format of the database of v6 and v2005 is the same. So it should be fine. You can restore the database archive and access using the new version of VSS client.


text:
Q: Making JDialog have continuoulsly changing Text Like "working..." I have a simple JDialog with a progress bar and I want it to have a JLabel that goes like:
Working. --> Working.. --> Working...
about every .25 seconds.
Would I just run a continuous loop repeatedly setting the JLabel's text?
I know this must be a simple solution, but I cannot seem to find it anywhere!
Per @David's response below. Here is the bulk of my WorkingDialog (which extends JDialog) constructor:
    final JLabel lblWorking = new JLabel("Working.");
    contentPanel.add(lblWorking, gbc_lblWorking);

    SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>()
    {

        @Override
        protected Void doInBackground() throws Exception
        {
            while (!isCancelled())
            {
                if (!lblWorking.getText().equals("Working..."))
                {
                    lblWorking.setText("Working.");
                } else
                {
                    lblWorking.setText(lblWorking.getText() + ".");
                }
            }

            return null;
        }
    };

    setVisible(true);
    sw.run();

And when I call new WorkingDialog() the frame comes up but thats about it. Does anyone know why?
Thanks,
Rich

A: Create a daemon that will update your label every 0.25 seconds. Dont forget to use SwingUtils.invokeLater() when updating the label.
I guess you should be able to do it with SwingWorker too.
Cheers


text:
Q: app crashes when loading in android unfortunately my app crashes when this activity is being loaded:
public class ManagerActivity extends Activity implements OnClickListener {

private TabHost th;

private EditText addpray1;
private EditText addplace1;
private EditText addtime1;
private Button addpray1Button;

private EditText removepray1;
private EditText removeplace1;
private EditText removetime1;
private Button removepray1Button;

private EditText addpray2;
private EditText addplace2;
private EditText addtime2;
private Button addpray2Button;

private EditText removepray2;
private EditText removeplace2;
private EditText removetime2;
private Button removepray2Button;

private EditText addtitlemessage;
private EditText addinfomessage;
private Button addmessagebutton;

private EditText removetitlemessage;
private Button removemessagebutton;

private EditText addtitleevent;
private EditText addinfoevent;
private Button addeventbutton;

private EditText removetitleevent;
private Button removeeventbutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.manager);

    th = (TabHost) findViewById(R.id.tabhost);

    InitTabs(th);
    InitFields();

    addpray1Button.setOnClickListener(this);
    removepray1Button.setOnClickListener(this);
    addpray2Button.setOnClickListener(this);
    removepray2Button.setOnClickListener(this);
    addeventbutton.setOnClickListener(this);
    removeeventbutton.setOnClickListener(this);
    addmessagebutton.setOnClickListener(this);
    removeeventbutton.setOnClickListener(this);
}

private void InitTabs(TabHost th){
    th.setup();

    TabSpec specs = th.newTabSpec("tag1");
    specs.setContent(R.id.tab1);
    specs.setIndicator("עדכון הודעות");
    th.addTab(specs);
    specs = th.newTabSpec("tag2");
    specs.setContent(R.id.tab2);
    specs.setIndicator("עדכון אירועים");
    th.addTab(specs);
    specs = th.newTabSpec("tag3");
    specs.setContent(R.id.tab3);
    specs.setIndicator("עדכון זמני השבת");
    th.addTab(specs);
    specs = th.newTabSpec("tag3");
    specs.setContent(R.id.tab4);
    specs.setIndicator("עדכון זמני יום חול");
    th.addTab(specs);

}

private void InitFields() {
    // TODO Auto-generated method stub

    addpray1 = (EditText) findViewById(R.id.addPray1);
    addplace1 = (EditText) findViewById(R.id.place1);
    addtime1 = (EditText) findViewById(R.id.time1);
    addpray1Button = (Button) findViewById(R.id.addPrayButton1);

    removepray1 = (EditText) findViewById(R.id.removePray1);
    removeplace1 = (EditText) findViewById(R.id.time_remove1);
    removetime1 = (EditText) findViewById(R.id.place_remove1);
    removepray1Button = (Button) findViewById(R.id.removePrayButton1);

    addpray2 = (EditText) findViewById(R.id.pray2);
    addplace2 = (EditText) findViewById(R.id.place2);
    addtime2 = (EditText) findViewById(R.id.time2);
    addpray2Button = (Button) findViewById(R.id.addPrayButton2);

    removepray2 = (EditText) findViewById(R.id.removePray2);
    removeplace2 = (EditText) findViewById(R.id.place_remove2);
    removetime2 = (EditText) findViewById(R.id.time_remove2);
    removepray2Button = (Button) findViewById(R.id.removePrayButton2);

    addtitlemessage = (EditText) findViewById(R.id.titleMessage);
    addinfomessage = (EditText) findViewById(R.id.messageInfo);
    addmessagebutton = (Button) findViewById(R.id.addMessageButton);

    removetitlemessage = (EditText) findViewById(R.id.removeMessage);
    removemessagebutton = (Button) findViewById(R.id.removeMessageButton);

    addtitleevent = (EditText) findViewById(R.id.addEvent);
    addinfoevent = (EditText) findViewById(R.id.eventInfo);
    addeventbutton = (Button) findViewById(R.id.addEventButton);

    removetitleevent = (EditText) findViewById(R.id.removeEvent);
    removeeventbutton = (Button) findViewById(R.id.removeEventButton);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

and the xml file :
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   <ProgressBar
    android:id="@+id/progressbar"
    style="@android:style/Widget.ProgressBar.Horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TabHost
    android:id="@+id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:weightSum="2" >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/addMessage"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הוספת הודעה"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/titleMessage"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/addMessage"
                        android:hint="כותרת"
                        android:lines="1"
                        android:scrollHorizontally="false" />

                    <EditText
                        android:id="@+id/messageInfo"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/titleMessage"
                        android:hint="מידע"
                        android:lines="4"
                        android:scrollHorizontally="true" />

                    <Button
                        android:id="@+id/addMessageButton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/messageInfo"
                        android:layout_centerInParent="true"
                        android:text="הוסף" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/removeMessage"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הסרת הודעה"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/titleMessage_remove"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/removeMessage"
                        android:hint="כותרת"
                        android:lines="1"
                        android:scrollHorizontally="false" />

                    <Button
                        android:id="@+id/removeMessageButton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/titleMessage_remove"
                        android:layout_centerInParent="true"
                        android:text="הסר" />
                </RelativeLayout>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:weightSum="2" >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/addEvent"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הוספת אירוע"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/titleEvent"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/addEvent"
                        android:hint="כותרת"
                        android:lines="1"
                        android:scrollHorizontally="false" />

                    <EditText
                        android:id="@+id/eventInfo"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/titleEvent"
                        android:hint="מידע"
                        android:lines="4"
                        android:scrollHorizontally="true" />

                    <Button
                        android:id="@+id/addEventButton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/eventInfo"
                        android:layout_centerInParent="true"
                        android:text="הוסף" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/removeEvent"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הסרת אירוע"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/titleEvent_remove"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/removeEvent"
                        android:hint="כותרת"
                        android:lines="1"
                        android:scrollHorizontally="false" />

                    <Button
                        android:id="@+id/removeEventButton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/titleEvent_remove"
                        android:layout_centerInParent="true"
                        android:text="הסר" />
                </RelativeLayout>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:weightSum="2" >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/addPray1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הוספת תפילה"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/pray1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/addPray1"
                        android:hint="תפילה" />

                    <EditText
                        android:id="@+id/place1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/pray1"
                        android:hint="מקום" />

                    <EditText
                        android:id="@+id/time1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/place1"
                        android:hint="שעה" />

                    <Button
                        android:id="@+id/addPrayButton1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/time1"
                        android:layout_centerInParent="true"
                        android:text="הוסף" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/removePray1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הסרת תפילה"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/pray_remove1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/removePray1"
                        android:hint="תפילה" />

                    <EditText
                        android:id="@+id/place_remove1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/pray_remove1"
                        android:hint="מקום" />

                    <EditText
                        android:id="@+id/time_remove1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/place_remove1"
                        android:hint="שעה" />

                    <Button
                        android:id="@+id/removePrayButton1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/time_remove1"
                        android:layout_centerInParent="true"
                        android:text="הסר" />
                </RelativeLayout>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab4"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:weightSum="2" >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/addPray2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הוספת תפילה"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/pray2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/addPray2"
                        android:hint="תפילה" />

                    <EditText
                        android:id="@+id/place2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/pray2"
                        android:hint="מקום" />

                    <EditText
                        android:id="@+id/time2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/place2"
                        android:hint="שעה" />

                    <Button
                        android:id="@+id/addPrayButton2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/time2"
                        android:layout_centerInParent="true"
                        android:text="הוסף" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" >

                    <TextView
                        android:id="@+id/removePray2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentTop="true"
                        android:text="הסרת תפילה"
                        android:textSize="25sp" />

                    <EditText
                        android:id="@+id/pray_remove2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/removePray2"
                        android:hint="תפילה" />

                    <EditText
                        android:id="@+id/place_remove2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/pray_remove2"
                        android:hint="מקום" />

                    <EditText
                        android:id="@+id/time_remove2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/place_remove2"
                        android:hint="שעה" />

                    <Button
                        android:id="@+id/removePrayButton2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/time_remove2"
                        android:layout_centerInParent="true"
                        android:text="הסר" />
                </RelativeLayout>
            </LinearLayout>
        </FrameLayout>
      </LinearLayout>
    </TabHost>

   </LinearLayout>

i guess it's because i'm loading a lot of views...
I'm also wanna to add a progress bar that works while the layout is loading until its done.
how can i fix that?
thanks :)


text:
Q: addAll to Set is not adding the values in java I have a property in an Object(Obj1)
Set<AssignedService> serviceList;
public Set<AssignedService> getServiceList();

I am doing the below operation in certain instances
Obj1.getServiceList().clear();
Obj1.getServiceList().addAll(services);

where Services is also Set
But what I see as an end result is services set is having 4 objects/data elements
but Obj1.getServiceList() is returning an empty set after addAll
What's the issue here. is it a problem with AssignedService object since it doesn't implements IComparable

A: You should first read this excellent piece on .equals()
Then, as others have pointed out, check your implementation of equals() and .hashcode() on the AssignedService class. Most likely the root cause is found here.
You could also check the return value of the .addAll(...) call - false would indicate that the underlying Set isn't modified by the method call.
Cheers,

A: Check the implementation of equals() in AssignedService.
Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.


text:
Q: C++ docking windows is there any way to dock two windows(like Winamp does with panels), but one window is from my application(WinApi) and second is from other(not connected with my app) application? So if I move window from other app my window will "glue" with it and move same direction.

A: I don't know if this is possible in C++ because I program in C# but what you could try is:
Make 2 panels.
Dock panel2 to the bottom.
dock panel1 to fill.
Place a splitter above panel2 so it can be resized.
I've used this solution before and it worked pretty well :).

A: Yes, that's fairly easy. Use SetWindowsHookEx(WH_CALLWNDPROCRET, otherHWND) to get the WM_MOVE message that will be generated whenever otherHWND moves.


text:
Q: Javascript filtering content on checkbox value I have code like this

Orange

Banana

I would like to filter divs with class "item" on its childs img src values. For example, If I checked input witch value banana.png only .item with same img src value should be displayed. Rest must be hidden.
And if you uncheck checkbox, control should be make again - items that were hided by checking that checkobox should be displayed again.
I have got same code that creates proper checkboxes, but how to make rest?
$("#items > div").find("img").each(function() {
    var value = $(this).attr("src");
    $("#filter").append('<input type="checkbox" [value="' + value + '"]>' + value + '');
    var toFilter = $("#items > div").find("img");
});

You can see my codepen as well http://codepen.io/anon/pen/gMpGaE?editors=0010

A: You can filter the div's like this using the change event of checkboxes.

$("#items > div").find("img").each(function() {
  var value = $(this).attr("src");
  $("#filter").append('<input type="checkbox" value="' + value + '">' + value + '');
  var toFilter = $("#items > div").find("img");
});
$('#filter').on('change', ':checkbox', function() {
  var checkedArray = $('#filter :checkbox:checked').map(function() {
    return this.value;
  }).get();
  if (checkedArray.length) {
    $("#items .item").hide();
    match = $("#items > div").find("img")
      .filter(function() {
        return checkedArray.indexOf($(this).attr('src')) != -1;
      }).closest('.item').show();
  } else {
    $("#items .item").show();
  }
})
#items > div {
  border: 1px dotted #355B78;
  margin-bottom: 10px;
}
label {
  display: block;
}

Orange

Banana

Orange

Banana


text:
Q: xhr Request call multiple time I am creating one profile page which have one logo using image tag. I need to change the logo by clicking the image and select the new one.
Current Implementation:

*

*I used file upload control and hide the element.

*When user clicks the logo i called the click event of file upload.

*In the onChange event of file upload control, I submit the closes form

*I track the form submit event and send using xhr request for Ajax post with image

Html Code:

  @using (Ajax.BeginForm("UpdateImage", "Account", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "successImage" }, new { enctype = "multipart/form-data" }))
   {

    <input id="profile-image-upload" name="image" class="hidden" type="file" onchange="$(this).closest('form').submit();">

click here to change image

   }

JQuery Code:
$(function () {
 $("form").submit(function (e) {
 e.preventDefault();
 var form = e.target;
 if (form.getAttribute("enctype") === "multipart/form-data") {
    var file = $(form).find('#profile-image-upload');
    if (!validateImage(file)) {
        return false;
    }
    if (form.dataset.ajax) {
      e.stopImmediatePropagation();
      var xhr = new XMLHttpRequest();
      xhr.open(form.method, form.action);
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var result = JSON.parse(xhr.response);
        successIamge(result);
        return false;
      }
    };
    xhr.send(new FormData(form));
    }
  }
 });

$('#profile-image1').on('click', function () {
  $('#profile-image-upload').click();
});

function successImage(result) {
  if (!result || !result.resultCode) return; //If result is null not handled or Validation handled via ModelState
  if (result.resultCode == 1) {
    // $('profile-image1').attr('src', result.resultValue);
     location.reload();
        }
  else {
     location.href = "/Error/Index?errorMessage=" + result.resultMessage;
        }
 }

Current Issue :
Process worked successfully but after response the image, again the post request is fired.
Work Around I did:
From  guest271314 question i found that i din't prevent default form submit. So now added the prevent default to the submit. I changed the code source above.
   Now the image is not updated with new image i got the response from the upload. So now i changed the sucessLogo method to reload the page got the new image.
Now please suggest any other method to update image with out reload the page


text:
Q: Управление процессом из winapi Нужно как-то из main управлять другим процессом. Читал, что есть CreateProcess, но инфы очень мало и непонятно. Может кто знает какой функцией говорить процессу: создай дерево, вставь туды элемент 11, удали элемент 14 и т.д. и т.п.
Тут важно понимать, что использование потоков - не прокатит!
(Спасибо, Sergey Gornostaev, очень помог, но как оказалось - нужно через процессы. НО! за знания отдельное огромное спасибо, хоть разобрался с потоками.)


text:
Q: React Redux: Cannot read property 'props' of undefined For some background info, I am new to Redux however I have already implemented a redux function in a different class for my same project. The error lies in the handleDragStop function where this.props is undefined.  I am sure that the action setSpotifySelectedTrackFeature is valid as I made it based on the same procedure I have followed before. The only difference being this component defined as a const as opposed to a class (in which I used redux function successfully) which I believe is the problem. Can anyone guide me with this? Thank you
import React,{useState} from 'react'

import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import {setSpotifySelectedTrackFeature} from "../actions/index";

import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Slider from '@material-ui/core/Slider';
import HelpIcon from '@material-ui/icons/Help';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';

function valuetext(value) {
  return `${value}`;
}

const useStyles = makeStyles({
  root: {
    width: 300
  },
});

function SpotifyRangeSlider(details) {
  const classes = useStyles();
  const [value, setValue] = useState([35, 65]);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const handleDragStop = (event, value) => {
    this.props.setSpotifySelectedTrackFeature(
        {
          "name": details.sliderLabel,
          "min": value[0],
          "max": value[1],
          "details": details.sliderDetails
        }
    )
    console.log("updated")
  }

  return (
    <div className="slider">
      <Typography id="range-slider" gutterBottom>
        {details.sliderLabel}
       <Tooltip title={details.sliderDetails}>
          <IconButton>
            <HelpIcon />
          </IconButton>
       </Tooltip>
      </Typography>
      <Slider
        value={value}
        onChange={handleChange}
        onChangeCommitted={handleDragStop}
        valueLabelDisplay="auto"
        aria-labelledby="range-slider"
        getAriaValueText={valuetext}
      />
    </div>
  );
}

//Used to retrieve data from the store(reducers)
function mapStateToProps(state){
  return{
    spotifySelectedTrackReducer: state.spotifySelectedTrackReducer
  };
}

//Used to send data so that an action can be called
function matchDispatchToProps(dispatch){
  return {
      ...bindActionCreators({setSpotifySelectedTrackFeature}, dispatch)
  };
}

export default connect(mapStateToProps, matchDispatchToProps)(SpotifyRangeSlider)

A: The issue is that you you are trying to reference this.props in a functional, non-class component. There is no this.props for a functional component, similar to how you couldn't really do this.state in this component either. Try instead accessing the mapped state to prop spotifySelectedTrackReducer via the functional component props, in this case you called them details:
const handleDragStop = (event, value) => {
  details.setSpotifySelectedTrackFeature(
    {
      "name": details.sliderLabel,
      "min": value[0],
      "max": value[1],
      "details": details.sliderDetails
    }
  )
  console.log("updated")
}

At minimum try logging out the value of details and see what props are available. Another option is to use react-redux hooks to get values from the store, which can be easier:
import { useDispatch, useSelector } from 'react-redux'

// ...
function SpotifyRangeSlider(details) {
  const spotifySelectedTrackReducer = useSelector(state => state.spotifySelectedTrackReducer)
  // ...
  // dispatch action using a hook also
  const dispatch = useDispatch()
  dispatch(setSpotifySelectedTrackFeature(someArguments))

Hopefully that helps!

A: I the current context details is the parameter which you are receiving as props. And we use this.props when we are using class components but you are using FunctionComponent. So, I think it should be details.setSpotifySelectedTrackFeature instead of this.props.setSpotifySelectedTrackFeature

A: There is no this.props in funtional components. They look like this:
function MyFuntionalComponent(props) {
  console.log(props.someThing)
}

//You can also destructure them how I like it
function MyFuntionalComponent({ name, id, someThing }) {
  console.log(someThing)
}


text:
Q: Wouldn't Aunt Petunia know that Harry couldn't use magic outside school? The answers to this question got me thinking. Aunt Petunia probably spent her childhood with Lily and though she was bitter, was probably in close contact with her at least until she finished Hogwarts. Wouldn't she have known beforehand that they weren't allowed to use magic outside of school?

A: Lily actually broke the rules several times and did magic outside of school. As Petunia screams in Philosopher's Stone:

"Oh, she got a letter just like that and disappeared off to that – that school – and came home every holiday with her pockets full of frog-spawn, turning teacups into rats."

JK Rowling was apparently asked about this enough that it became an FAQ on her website, in which she reveals that Aunt Petunia was telling the truth. Lily really did do magic outside of school.

Aunt Petunia is exaggerating a little; you have to allow for her state of mind when she started shrieking these things. However, just like her son, Lily was not averse to testing the limits of the Statute of Secrecy, so you can safely assume she will have had a few warning letters – nothing too serious, though.

Petunia may have seen the magic as a child, but not realized what the letters Lily was receiving were saying.

A: She definitely knew once, but seems to have forgotten.
We know from memories we see in the final book that Petunia overheard a conversation in which Lily was told about the Statute of Secrecy, and how she couldn't do magic outside school:

"…and the Ministry can punish you if you do magic outside school, you get letters."
"But I have done magic outside school!"
"We're all right. We haven't got wands yet. They let you off when you're a kid and you can't help it. But once you're eleven," he nodded importantly, "and they start training you, then you've got to go careful." […]
Then a small rustling noise behind Harry made him turn: Petunia, hiding behind a tree, had lost her footing.
— Deathly Hallows, chapter 33 (The Prince's Tale)

So she knew about this rule at some point.
But when Hagrid arrives to take Harry to school (about twenty years later), the way Petunia describes it sounds as if Lily was doing magic outside school:

"How could you not be, my dratted sister being what she was? Oh, she got a letter just like that and disappeared off to that – that school – and came home every holiday with her pockets full of frog-spawn, turning teacups into rats."
— Philosopher's Stone, chapter 4 (The Keeper of the Keys)

When Harry receives his letter from the Ministry, it also sounds as if all the Dursleys, including Petunia, are concerned that Harry would use magic outside school:

"You didn't tell us you weren't allowed to use magic outside school," said Uncle Vernon, a mad gleam dancing in his eyes. "Forgot to mention it…. Slipped your mind, I daresay…." […]
Life at Privet Drive had reached an all-time low. Now that the Dursleys knew they weren't going to wake up as fruit bats, he had lost his only weapon.
— Chamber of Secrets, chapter 2 (Dobby's Warning)

So it seems that she really has forgotten.
I would guess that when she married Vernon, Petunia tried to push all knowledge of the magical world to the back of her mind. It may also have helped if Vernon, paranoid as he is, kept talking about the possibility that Harry would use his magic against them.
Alternatively, given that Vernon and Petunia don't set much store by Harry, his parents or the magical world in general, she could have convinced themselves that Harry would ignore this law without any real consequence, so legitimising the fear.

A: I would also like to point out that even though Harry isn't allowed to do magic outside of school, he is still capable of it. It's not like they had any way of stopping him if he tried.
But I agree more with the above answers in that she merely forgot. It never pertained to her and she did see Lily doing magic.
Side note: I would wager that small magic of no consequence would have been overlooked/ not even reported to the ministry. Hermione, when she first met the boys on the train says something along the lines of
 Of course, I've only tried a few simple spells myself, but they've all worked for me.

(if anyone has the direct quote feel free to edit this, I don't have the books with me.)
Indicating that even with a wand/ being 11 and of Hogwarts age, it's not like kids weren't casting spells. But really, who wants to expell a kid for turning tea cups into rats (and probably bad ones with them being so young)
Of course Petunia would have no way of classifying spells and as far as she was concerned, even if she remembered the rules, they weren't enforced.

A: Everyone seems correct here.. I would like to add that turning teacups into rats is advanced transfiguration.. Maybe Lily was of age when she did such things at home.. Petunia didn't know wizards turn of age earlier than Muggles, so she probably retained the impression that Lily did magic in vacations at home..


text:
Q: Drawing text inside D3 rect element? I have code here and I need to add text into the rect element on the right of all the hexagons and have it act like a paragraph inside of a div with a given height and width and have it wrap properly. Here is the jsfiddle. and the code that draws the rect is below:
http://jsfiddle.net/2nykc/
var infoRect = svgContainer.append("rect");
    var infoRectAttr = infoRect.attr("x", function(){
        return infoDivX;
    })
    .attr("y", function(){
        return infoDivY;
    })
    .attr("width", function(){
        return infoDivWidth;
    })
    .attr("height", function(){
        return infoDivHeight;
    })
    .style("fill", "rgb(30,180,134)")
    .style("stroke", "black")
    .style("stroke-width", 3)
    .attr("id", "infoRect");


text:
Q: Displaying PHP results? I need a little help here with some php.
just a little explanation:
(im trying to display 5 results using this code
    $n_id = mysql_real_escape_string ($_GET['id']);
    $path = '';

    if(isset($n_id) && $n_id != "") {
        $sql = 'SELECT * FROM test2 WHERE id="' . $n_id . '"';
        $news = mysql_query($sql);

    if($result = mysql_fetch_array($news)) {
        $title = mysql_result($news,0,"title");
        $date = mysql_result($news,0,"date");
        echo '' . $title . ' | ' . $date . '

        ';
    } else {
        header("Location: vendi.php");
    }
    echo '
Back to Archive';
    }

It does display but i want that 1st result to be (image+title of the news and other results to be just title).
Hope i wrote it clearly what i needed help with.
Thank you

A: Your SQL statement is only fetching a single row. This isn't a complete solution, but should get you closer:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $n_id = (int)$_GET['id'];
    $path = '';

    $count = 0;

    $sql = 'SELECT * FROM test2 WHERE id BETWEEN ' . $n_id ' AND ' . ($n_id + 5);
    $news = mysql_query($sql);

    while ($result = mysql_fetch_array($news)) {
        $title = $result['title'];
        $date = $result['date'];
        echo '' . $title . ' | ' . $date . '';
        if ($count < 1) {
            echo '
';
            $count++;
        }
    }

    if ($count == 0) { header("Location: vendi.php"); }

    echo '
Back to Archive';
}

A: While looping through your results, you can check if you are at the first result:
$counter = 0;
while ($row = mysql_fetch_array($news)) {
    $title = mysql_result($news,0,"title");
    $date = mysql_result($news,0,"date");
    echo '' . $title . ' | ' . $date . '';
    if ( $counter == 0 ) {
        echo '
';
    }

}

A: This should do it.
$n_id = mysql_real_escape_string ($_GET['id']);
    $path = '';

    if(isset($n_id) && $n_id != "") {
        $sql = 'SELECT * FROM test2 WHERE id="' . $n_id . '"';
        $news = mysql_query($sql);

        $first = TRUE;
        if($result = mysql_fetch_array($news)) {
            $title = mysql_result($news,0,"title");
            $date = mysql_result($news,0,"date");

            if($first == TRUE) {
                echo '' . $title . ' | ' . $date . '';
                $first = FALSE;
            }
            else {
                echo '' . $title . ' | ' . $date . '

                ';
            }
        }
        else {
            header("Location: vendi.php");
        }
        echo '
Back to Archive';
        }
    }


text:
Q: Libgdx "pack", not working, what I could be doing wrong? I'm trying to make a window, then use the pack method to get the right size, but the window maximizes instead. Here's my code:
private Table buildOptionsWindowLayer() {
    winOptions = new Window("Options", skinLibgdx);
    // (...) building some widgets

    Gdx.app.log(TAG, "pref width is " + winOptions.getPrefWidth());
    // displays: "pref width is 247.0"

    winOptions.pack();

    // move the window
    winOptions.setPosition(Constants.VIEWPORT_GUI_HEIGHT - winOptions.getWidth() - 50, 50);
    return winOptions;
}

The window ends up with a width of 800.0f. Why?
What it is supposed to render:

What it does render:

A: Give the pack() documentation a read. I believe your .pack is the problem here as it calls the super class' constructor before yours.

A: I know this is an old thread, but I just ran into this same issue.  You can move the pack and position calls to the onOptionsClicked method so they are called after the window is shown.
private void onOptionsClicked()
{
    loadSettings();
    btnMenuPlay.setVisible(false);
    btnMenuOptions.setVisible(false);
    winOptions.setVisible(true);

    winOptions.pack();
    winOptions.setPosition(Constants.VIEWPORT_GUI_WIDTH - winOptions.getWidth() - 50, 50);
}


text:
Q: Call 'wp_logout' when cookie expires (php or javascript) I am looking for a way to call wp_logout (server side) if my wordpress_logged_in_HASH cookie expires. Unfortunalty I can't find any solution so far. Did a lot of research on stackoverflow and google, but still not done.
Does anyone have some advices or ideas how to do it?
Server side I can check if the cookie exits with $_SERVER['HTTP_COOKIE']. The variable exits on my shared server and this works. But how to run wp_logout automaticly when cookie expires? Maybe by some javascript?
if(strpos($_SERVER['HTTP_COOKIE'], 'wordpress_logged_in') == true){
    echo "Login cookie exists!<br>";
    var_dump($_SERVER['HTTP_COOKIE']);
    //echo($startTime = microtime(true));
} else{
    echo "Login cookie not exists!";
    var_dump($_SERVER['HTTP_COOKIE']);
    }

A: Simply change session expire time, as mentioned, by adding in your theme's functions.php something like:
add_filter('auth_cookie_expiration', 'my_expiration_filter', 99, 3);
function my_expiration_filter($seconds, $user_id, $remember){

    //if "remember me" is checked;
    if ( $remember ) {
        //WP defaults to 2 weeks;
        $expiration = 14*24*60*60; //UPDATE HERE;
    } else {
        //WP defaults to 48 hrs/2 days;
        $expiration = 2*24*60*60; //UPDATE HERE;
    }

    //http://en.wikipedia.org/wiki/Year_2038_problem
    if ( PHP_INT_MAX - time() < $expiration ) {
        //Fix to a little bit earlier!
        $expiration =  PHP_INT_MAX - time() - 5;
    }

    return $expiration;
}

Surprisingly enough, WordPress does not use PHP sessions at all. It uses only cookies. And it uses a number of them with hashed names.
So don't mess with them directly, and do it the WordPress way with filters like above.
Or by calling WordPress APIs. E.g. if you want to log out the current user, you can call wp_clear_auth_cookie:
http://codex.wordpress.org/Function_Reference/wp_clear_auth_cookie


text:
Q: "A descriptive string set at run-time. Don't localize."? When I open Safari, in my Bookmarks tab it shows me a pop-up:

What does this mean?

A: It appears to be an internal testing message for localization. Are you using a beta version of Safari? or have you in the past? It may be a case of resetting safari content if so.


text:
Q: Need help sorting a php array by age My code:
$friends = [
    ['first_name' => "Cassidy", 'last_name' => "Nelson", 'age' => 21],
    ['first_name' => "Kyler", 'last_name' => "Besher", 'age' => 22],
    ['first_name' => "Caitlin", 'last_name' => "McGonigal", 'age' => 19],
    ['first_name' => "Matt", 'last_name' => "Miller", 'age' => 30],
    ['first_name' => "Skyler", 'last_name' =>"Stucky", 'age' => 22]
];

asort($friends);
foreach ($friends as 'first_name' => 'age' {
    echo "$key = $val\n";
}

So I am completely new to PHP so this is probably going to be a pretty dumb question but I am trying to sort the friends within my friends array in order by age while also displaying their first names. What am I doing wrong?


text:
Q: How to use 'onKeyUp' attribute in asp.net?
Message    1:  Validation (ASP.Net): Attribute 'onkeyup' is not a valid attribute of element 'TextBox'.    E:\ABC\ABCD.aspx    83  66  ABCD

I want dropdown to change the Display list according to the value typed in TextBox.I have written the following query for it
var ddlText, ddlValue, ddl, lblMesg;

function CacheItems() {
    ddlText = new Array();
    ddlValue = new Array();
    ddl = document.getElementById("=STCDropDownList.ClientID");
    lblMesg = document.getElementById("=Label1.ClientID");

    for (var i = 0; i < ddl.options.length; i++) {
        ddlText[ddlText.length] = ddl.options[i].text;
        ddlValue[ddlValue.length] = ddl.options[i].value;
    }
}

window.onload = CacheItems;

function FilterItems(value) {
    ddl.options.length = 0;
    for (var i = 0; i < ddlText.length; i++) {
        if (ddlText[i].toLowerCase().indexOf(value) != -1) {
            AddItem(ddlText[i], ddlValue[i]);
        }
    }

    lblMesg.innerHTML = ddl.options.length + " item(s) found.";

    if (ddl.options.length == 0) {
        AddItem("No item found.", "");
    }
}

function AddItem(text, value) {
    var opt = document.createElement("option");
    opt.text = text;
    opt.value = value;
    ddl.options.add(opt);
}

The below following are Textbox and DropDownlist i am using.
        <asp:TextBox ID="STCTextBox" runat="server"  onkeyup="FilterItems(this.value)"></asp:TextBox>

    Service Tax Code

        <asp:DropDownList ID="STCDropDownList" runat="server" AutoPostBack="True" DataSourceID="STCSqlDataSource" DataTextField="ServiceTaxCode" DataValueField="ServiceTaxCode"></asp:DropDownList>
        <asp:Label ID="Label1" runat="server" Text="Entered Comm Code Already Registered" Visible="False"></asp:Label>

A: Simple jQuery Function
.keyup()

Explore https://api.jquery.com/keyup/

A: From What i see
Replacing Function FilterItems with this can help
var txtBox=document.getElementById("=STCTextBox.ClientID");

txtBox.onkeyup=function() {
var value=txtBox.value;

    ddl.options.length = 0;
    for (var i = 0; i < ddlText.length; i++) {
        if (ddlText[i].toLowerCase().indexOf(value) != -1) {
            AddItem(ddlText[i], ddlValue[i]);
        }
    }

    lblMesg.innerHTML = ddl.options.length + " item(s) found.";

    if (ddl.options.length == 0) {
        AddItem("No item found.", "");
    }
}

A: Rather use jQuery:
$("#id").keyup(function(){

        // Your Code

});


text:
Q: svchost.exe runs at 90% CPU, tasklist /svc shows RpcSs is the culprit I'm running Windows Server 2003 Standard (Much to my distaste), I've applied all the security updates and now I'm stuck with a box that's constantly being hammered by svchost.
The process ID is always around the 700 mark and if I use tasklist /svc, I can see that RpcSs is causing it.
I have tried various things that have come up in google searches such as turning automatic software update services off, removal of antivirus software, removal of systray items, removal of remote screen services such as RDP, VNC, LogMeIn etc.
I'm still stuck with this RpcSs running at 90%, I'm completely at the end of my tether with this now but I don't really want to sit through a complete re-install just to see if it happens again.

A: You might try using the Sysinternals tools Process Explorer and Process Monitor. For example, in Process Explorer - select the relevant svchost.exe instance, right click and choose properties and then go to the Threads tab. You may see a dll name in there that gives you a clue.

A: I have seemn some malware use this process and we had to use a bootable disk with the Syamantec Endpoint Recovery Tool and current defs to remove.  It was some kind of rootkit that slipped by the installed AV.


text:
Q: How to get pandas dataframe by chunks from csv files in huge tar.gz without unzipping and iterating over them? I have a huge compressed file on which I am interested in reading the individual dataframes, so as not to run out of memory.
Also, due to time and space, I can't unzip the .tar.gz.
This is the code I've got this far:
import pandas as pd
# With this lib we can navigate on a compressed files
# without even extracting its content
import tarfile
import io

tar_file = tarfile.open(r'\\path\to\the\tar\file.tar.gz')

# With the following code we can iterate over the csv contained in the compressed file
def generate_individual_df(tar_file):
    return \
        (
            (
                member.name, \
                pd.read_csv(io.StringIO(tar_file.extractfile(member).read().decode('ascii')), header=None)
            )
               for member in tar_file
                   if member.isreg()\
        )

for filename, dataframe in generate_individual_df(tar_file):
    # But dataframe is the whole file, which is too big

Tried the How to create Panda Dataframe from csv that is compressed in tar.gz? but still can't solve ...

A: You actually can iterate over the chunks inside a compressed file with the following function:
def generate_individual_df(tar_file, chunksize=10**4):
    return \
        (
            (
                member.name, \
                chunk
            )
            for member in tar_file
                if member.isreg()\
                for chunk in pd.read_csv(io.StringIO(tar_file.extractfile(member)\
                  .read().decode('ascii')), header=None, chunksize=chunksize)
        )


text:
Q: Spreadsheet Functions converts dates into text I am using spreadsheet functions for my Excel reports, but it converts dates into text when exported to Excel. So, I used datatype 'Date' in SpreadSheetSetCellValue, so the values in the first column can be converted into any date format the customer wants. Here is the code:
 <cfset SpreadsheetSetCellValue(objSheet, '#RecordDate#', iRow, 1, 'Date')>

This works fine, but when I later apply a background color to alternate rows:
<cfset stFormat.AlternateRow = StructNew()>
<cfset stFormat.AlternateRow.fgcolor = 'yellow'>

<cfif (iRow mod 2) IS 0>
    <cfset SpreadsheetFormatRow(objSheet, stFormat.AlternateRow, iRow)>
</cfif>

It converts all of the columns in that row to 'date' format. Whereas I only want the 1st column, in each row, to be of 'date' datetype.

A: Sounds like a bug to me.  I'd put together a repro case and submit a bug bugbase.adobe.com.
Though not ideal, one possible workaround is to set the date column value after formatting the row. Unfortunately setting the cell value also wipes out the background color, so you need to reapply that as well. Tested with CF11, YMMV.
NB: The workaround doesn't change the order of the columns at all, only when they're formatted. So the "date" still ends up in the 1st column.
Runnable Example on TryCF.com
<cfscript>
    objSheet = SpreadSheetNew("Sheet1", true);
    for(iRow = 1; iRow <= 100; iRow++) {

        // populate everything EXCEPT the date column
        SpreadsheetSetCellValue(objSheet, "B", iRow, 2);
        SpreadsheetSetCellValue(objSheet, "C", iRow, 3);
        SpreadsheetSetCellValue(objSheet, "D", iRow, 4);
        SpreadsheetSetCellValue(objSheet, "1234", iRow, 5);

        isAlternateRow = (iRow MOD 2) EQ 0;
        rowColor = isAlternateRow ? 'yellow' : 'white';

        // format whole row
        if (isAlternateRow) {
            SpreadsheetFormatRow(objSheet, { fgcolor = rowColor }, iRow);
        }

        // finally apply date and reformat that cell
        SpreadsheetSetCellValue(objSheet, now(), iRow, 1, 'date');
        SpreadSheetFormatCell(objSheet, { dataformat = 'mm-dd-yyyy', fgcolor = rowColor}, iRow, 1);
    }
</cfscript>

Results:


text:
Q: Seeking Colombia municipality geometries I'm looking for shapefiles (or some similar format) of Colombia's municipality boundaries.
Wikipedia has a map that seems to be correct and which matches another dataset that I will eventually be merging in based on municipality names and DANE codes. I've tried contacting the file creator about the underlying source data, but without success.
I've tried GADM, but some of the municipalities are missing/incorrect, e.g. all the way in the South Amazons should have 11 municipalities, not 8.

Here's OpenStreeMap with data export via Mapzen. Many municipalities are simply just missing, although the borders for those that are there appear to be correct and more detailed than GADM.

I guess I could try to combine departments that OpenStreeMap had all municipalities for with the GADM data, but it looks like that would still only partially get me there. And in general it just makes me a bit suspicious about using the GADM data at all.

A: You can try the WFS or WMS servers of the Instituto Geográfico Agustín Codazzi (here:http://www.igac.gov.co/wps/portal/igac/raiz/iniciohome/MapasdeColombia/Descargas).
These services have different layers for geodesic features and demographics.
If that doesn't work, you can check this link with the shapefile I use for Colombian municipalities: https://www.dropbox.com/sh/i0ao837gj5wpkic/AAAnzZf-tJIKUmZvTKrvXPMpa?dl=0

A: In case someone else serves you, here are a set of examples you create visualizing the municipalities of Colombia from a geojson file that I managed to achieve
https://bl.ocks.org/john-guerra/727e8992e9599b9d9f1dbfdc4c8e479e
If you look at my bl.ocks.org/john-warra you can see more examples, but stackexchange will not let me upload more than two links
And here's a react component you create to make it easy to create these maps
https://github.com/john-guerra/ColombiaVisualizationReact

A: Colombia's National Administrative Department of Statistics hosts shapefiles that have official municipality boundaries here: https://geoportal.dane.gov.co/?descarga-marco-geoestadistico-nacional
Also, as of today, GADM is still missing municipalities in Amazonas, and in the OpenStreetMap data, some municipal boundaries intersect their neighbors.
Edit: Possibly this link is nicer (the CSS on the first link isn't great for some browsers/viewport sizes): https://geoportal.dane.gov.co/metadatos/descarga_mgn/

A: Districts/Boroughs in Bogotá are called Localidades. You can download them from the
Infraestructura de Datos Espaciales para el Distrito Capital * (IDECA) website, specifically here.
In the case of Medellín, these are called Comunas and can be found on the map catalogue's webpage from the town/municipal hall, specifically here.
* Roughly translates to Spatial Data Infraestrcuture for the Capital District.