text:
Q: Orchard overriding customform textarea template How to override/create customform textarea template?
Using Orchard 1.8. In order to style a custom form I wish to addclass to the fieldset tag wrapping the textarea. Using the shapetracer it is not clear to me
(I can override other  tags for example the 'boolean field types.
(E.g copy Modules/Orchard.Fields/Views/EditorTemplates/Fields/Boolean.Edit.cshtml to Views/EditorTemplates/Fields/Boolean.Edit.cshtml) but unsure for textarea. (copying Input.Edit.cshtml doesnt work it appears.)

A: You can override the TextArea by copying the file ~/Core/Common/Views/Body.Editor.cshtml to a location of higher priority (like ~/Themes/MyTheme/Views/Body.Editor.cshtml) and editing it there.  However, that cshtml file handles more than just TextArea type - it would override the rendering of all body editors.  To be specific to just textarea, you should create a file named Body.Editor-TextArea.cshtml

A: Usually, i just override the whole HTML. You know the names/ids right? so you can easily copy the HTML from the ShapeTracer and copy in your new Alternate.
While the name/ids stay the same, everything will wire up properly.
Check your "EditorTemplate", but before creating and alternate, copy the HTML instead of the Template.


text:
Q: Уменьшить размер apk с Yandex mapkit Использую в приложении Yandex mapkit
implementation 'com.yandex.android:maps.mobile:4.0.0-lite'

При сборке размер apk увеличился с 17Мб до 117Мб. С разработчиками связался, пока молчат. на GitHub нашёл их ответ:
Начиная с версии 3.1 мы разбили mapkit на части, которые можно подключать по отдельности. Теперь можно убрать directions, search, places и masstransit из build.gradle, если их функциональность не используется. Если получится убрать их все, размер должен уменьшиться раза в два.

Как можно убрать directions, search, places и masstransit из build.gradle?

redpajama_set_name: RedPajamaStackExchange


text:
Q: spring MVC, get the value of the rejected field from ObjectError I have already check the similar questions on so but I don't have anything matching.
I check if I have errors with:
result.getErrorCount() != 0)

and inside I have the list of errors using
List<ObjectError> ae = result.getAllErrors();

when I use the debug mode of eclipse and I check the field inside the list I have the good id in the form.
But at runtime I'm unable to get the value by doing
for (ObjectError fe : result.getAllErrors())
{
   fe.getField();
}

A: You need to cast ObjectError to FieldError and then you can retrieve the name of the affected field by calling getField().
JavaDoc for FieldError


text:
Q: ASP.NET MVC3: How do I hide fields using Html.DisplayForModel and Html.EditorForModel Using the following two methods in my view and edit views, They run off the model and automatically generate a list of the fields with labels, to display/edit.
  @Html.EditorForModel()

  @Html.DisplayForModel()

The problem is that they display every field.. Including the ID field, which is bad when it comes to editing as it should not be changed.
So, How do I hide certain fields in the model. (without removing the fields from the model.)

A: You can use the Scaffold Attribute
[ScaffoldColumn(false)]
public int Id {get;set;}

And if you also want that the model binder does not touch the Id field (to prevent over-posting) you can set the ReadOnly-Attribute too.
[ReadOnly(true)]
[ScaffoldColumn(false)]
public int Id {get;set;}


text:
Q: Statistical data like display in website from large record set I have 4 databases with tables having lots of data. My requirement is to show count of all the records in these tables on mouse hovering the corresponding div in UI(It is an asp.net website). Please note the count may change in every minute or in hour. (Means new records can be added or deleted from the table [using another application]). Now the issue is like, it is taking lot of time to get the count (since it has lots of data). So each mouse over, it is having a call to corresponding database and taking the count. Is there any better approach to implement this?
I am thinking of implementing something like as below.
http://www.worldometers.info/world-population/
But to change the figures like that in each second I need to have a call to the database. Right? (To get the latest count) Is there any better approach to show data like this statistics?
By the Way, I am using MySQL.
Thanks

A: You need to give more details - what table engines you are using, how does your count query look like, etc.
But assuming that you are using InnoDB, and you are trying to run count(*) or count(primary_id_column), you have to remember that InnoDB has clustered primary keys, that are stored with the data pages of the row itself, not in separate index pages, so the count will do full scan on the rows.
One thing you can try is to create additional, separate, not primary index on any unique column (like row's id etc,) and make sure (use explain query statement) that your count uses this index.
If this does not work for you, I would suggest to create separate table (for example with columns: table_name, row_count) to store counters in it and create triggers on insert and on delete on other tables (you need to count records in) to increment or decrement these values. From my experience (we monitor number of records in daily and hourly manners, on tables with hundreds of milions of records and heavy write load: ~150 inserts/sec) this is the best solution I have came up so far.


text:
Q: Spivak Calculus Chapter 9 Question 9(ii) I am working out of the 3rd edition. The question is to find $f'(x)$ and $f'(x+3)$ for $f(x+3)=x^5$
My working is the following:
$$\begin{eqnarray}
f(x)&=&f((x+3)-3)\\
&=&(x-3)^5\\
\implies f'(x)&=&5(x-3)^4\\
\end{eqnarray}$$
According to the answers section in the book, this is correct. Now:
$$\begin{eqnarray}
f'(x+3)&=&f'((x)+3)\\
&=&5((x+3)-3)^4\\
&=&5x^4\\
\end{eqnarray}$$
However, the answer in the back of the book for $f'(x+3)$ is $0$. I can't understand how the result $0$ was obtained at all. Is this a problem with the book, or a problem with my working? I can't find an up to date errata list.

A: The answer, of course, is wrong. You must have a very old edition of the book, as I don't remember encountering this in the later editions. Your work is fine. You can also do the second problem by introducing a new function $g$ by setting $f(x+3)=g(x)=x^5$. Then $f'(x+3)=g'(x)=5x^4$. (To see why $f'(x+3)=g'(x)$, just write down the definition of the derivatives.)


text:
Q: URL not matching url pattern in Django I'm trying to learn Django, went through the official tutorial and giving it a try on my own. I've created a new app and can access the index page but I can't use pattern matching to go to any other page. Here is my monthlyreport/url.py
from django.urls import path

from . import views

#app_name = 'monthlyreport'

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

and my monthlyreport/views
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic

from .models import Report

def index(request):
    report_list = Report.objects.all()[:5]
    template = loader.get_template('monthlyreport/index.html')
    context = {
        'report_list': report_list,
    }
    return HttpResponse(template.render(context, request))

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

The debug for http://127.0.0.1:8000/monthlyreport/0 is showing
 Using the URLconf defined in maxhelp.urls, Django tried these URL patterns, in this order:

 monthlyreport [name='index']
 monthlyreport <int:question_id>/ [name='detail']
 polls/
 admin/
 accounts/

 The current path, monthlyreport/0, didn't match any of these.

Again, using http://127.0.0.1:8000/monthlyreport/ to go to index works fine, but I cant match the integer. I would really appreciate any suggestions, I am very, very confused at this point.

A: Problem with your code is of one slash(/). In your root urls.py file, from where you must have used something like:
path('monthlyreport', include('monthlyreport.url'))

So, the problem here is that you should have ending / in your path if you are setting your urls in monthlyreport.url like:
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

Or else, you have to put slash(/) infront of every new path like:
urlpatterns = [
    path('', views.index, name='index'),
    path('/<int:question_id>/', views.detail, name='detail'),
          |
          |
          V
        Here
]

Solution
In summary, convinient solution is adding  slash(/) after path in urls.py file. Like:
path('monthlyreport/', include('monthlyreport.url'))
                   |
                   |
                   |
                   V
             Add slash here


text:
Q: How to remove blank columns and reorder the columns in desired order in powershell I got a excel sheet ,which got values from server . I want to remove columns which have no value..I did that but resulted excel sheet column names are in alphabetical order.But I want them in desired order. If use Select-object to get desired order , it will give the removed columns again.Below is the code i used to remove blank columns.
$x = Import-Csv YourFile.csv
$f = $x[0] | Get-Member -MemberType NoteProperty | Select name
$f | Add-Member -Name count -Type NoteProperty -Value 0
$f | %{
  $n = $_.Name
  $_.Count = @($x | Select $n -ExpandProperty $n | ? {$_ -ne ''}).count
}
$f = @($f | ? {$_.count -gt 0} | Select Name -expandproperty Name)

$x | Select $f | Export-Csv NewFile.csv -NoTypeInformation

A: As Axel Andersen points out, Get-Member invariably returns an object's members alphabetically sorted.
Try the following approach, which uses .psobject.Properties.Name to get the column (property) names in the original order:
$rows = Import-Csv YourFile.csv
$columnNames = $rows[0].psobject.Properties.Name

$nonEmptyColumnNames = $columnNames.Where({ (@($rows.$_) -ne '').Count -gt 0 })

$rows | Select-Object $nonEmptyColumnNames | Export-Csv NewFile.csv -NoTypeInformation


text:
Q: bootstrap nav-tabs + Swiper из трех вкладок Swiper работает нормально только в первой, в последующих же он как я понимаю не может посчитать ширину экрана.
Подскажите кто сталкивался, как правильно решить задачу.

Для дома

Для кафе

                    Для Отдыха

инициализирую три раза


text:
Q: How to parse gmail with specific subject line and get populated in the google sheets The Code which i have tried is not able to get the email with specific subject line please let me know what is the mistake in the script mentioned below
Tried the Below mentioned Script but still not working:
function amy() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var threads = GmailApp.search('subject: "New submission from Free Diagnosis*"');
  var a=[];
  for (var i = 0; i < threads.length; i++) {
    var messages = GmailApp.getMessagesForThread(threads[i]);
    for (var j = 0; j < messages.length; j++) {
      a[j]=parseMail(messages[j].getPlainBody());
    }
  }
  var nextRow=s.getDataRange().getLastRow()+1;
  var numRows=a.length;
  var numCols=a[0].length;
  s.getRange(nextRow,1,numRows,numCols).setValues(a);
}


text:
Q: Add a folder in a sequence of folders and rename the other folders I have x number of folders
folder1
folder2
folder3
......
folder100

What I want to do is;
add folder2
reorder

So now:
folder1
folder2
folder3
......
folder101

So now, the folder that was folder2 is folder3, and etc.
Example:
folder2 -> folder3, folder3 -> folder4, folder4 -> folder5
The folder1 remain intact.
To be more precise I want to automate this
$ mkdir 1 2 3 4 5
$ ls
1 2 3 4 5
$ mkdir 2_1
$ ls
1 2 2_1 3 4 5
$ mv 5 6
$ ls
1 2 2_1 3 4 6
$ mv 4 5
$ mv 3 4
$ mv 2 3
$ mv 2_1 2
$ ls
1 2 3 4 5 6
$

How do I do this in bash?

A: You could use a for.. clause with a brace expression for enumeration plus inline arithmetic; something like this:
for f in {100..2} ; do mv $f $((f+1)) ; done

That would take care of moving "up" all folders from 100 down to 2 one step.
More generically, you could use a script that discovers the insert point X from the folder name pattern X_1, and the highest number folder name before "making the hole". Something like this:
#!/bin/bash
X=*_1
F=( $(ls * | sort -nr) )
for f in {$F..${X%_1}} ; do mv $f $((f+1)) ; done
mv $X ${X%_1}

Note that $F is an array of all folder names, numerically sorted from highest to lowest number, so $F by itself is the highest number. Also, the format ${X%_1} means "$X with the ending _1 removed". The format $((f+1)) means "the value of f plus 1".
The script doesn't handle "insert" past the highest number.

A: With zsh:
autoload zmv # best in ~/.zshrc
zmv 'folder(<2->)(#q/nOn)' 'folder$(($1 + 1))' &&
  mkdir folder2

Or for your automatic renaming based on the presence of folder<n>_1 folders:
setopt extendedglob
for dir ([-._[:alpha:]]##<->_1(N/nOn)) {
  [[ $dir = (#b)(*)(<->)_1 ]]
  zmv "($match[1])(<$match[2]->)(#q/nOn)" '$1$(($2 + 1))' &&
    mv "$dir" "${dir%_1}" || break
}

Example:
before:
$ ls
bar1/  bar2/  bar2_1/  bar3/  foo1/  foo1_1/  foo1_3/  foo2/  foo3/  foo4/

after:
$ ls
bar1/  bar2/  bar3/  bar4/  foo1/  foo2/  foo3/  foo4/  foo5/  foo6/

A: Use regex with mkdir:
mkdir folder{1..100}
Then verify your output!
ls -l

folder1
folder2
folder3
..
folder100

A: I solved it like this
#!/bin/bash
for f in {100..2} ; do mv $f $((f+1)); done
x="?_1"
y=$(echo $x | cut -b 1-1)
mv $x $y

It's very manual, but solves faster the initial problem.


text:
Q: Count elements of nested array swift Does anyone know here how to count amount of elements in all nested array of custom objects in Swift?
I.e. I have
[Comments] array which includes [Attachments] array. There may be 100 comments and 5 attachments in each of them. What is the most Swifty way to count all attachments in all comments? I tried few solutions like flatMap, map, compactMap, filter, reduce, but couldn't figure out how to achieve the desire result. The only one that worked for me was typical for in loop.
    for comment in comments {
        attachmentsCount += comment.attachments.count
    }

Is there any better approach to achieve the same? Thanks

A: You can use reduce(_:_:) function of the Array to do that:
let attachementsCount = comments.reduce(0) { $0 + $1.attachments.count }

A: Here are two ways to do it based on using map
First with reduce
let count = comments.map(\.attachments.count).reduce(0, +)

And one variant using joined
let count = comments.map(\.attachments).joined().count


text:
Q: Custom directive is not working inside angular module? In my app, i have two modules. IdentityModule and ServiceModule. They are loaded as lazyloading technology.
Now I have created a custom directive IconSpacerDirective that is bind with app.module.ts. It's working fine inside my app.component.ts.
But it's not working inside the IdentityModule. I am having this error:
ERROR Error: Uncaught (in promise): Error: Type IconSpacerDirective is part of the declarations of 2 modules: AppModule and IdentityRegistryModule! Please consider moving IconSpacerDirective to a higher module that imports AppModule and IdentityRegistryModule. You can also create a new NgModule that exports and includes IconSpacerDirective then import that NgModule in AppModule and IdentityRegistryModule.
Error: Type IconSpacerDirective is part of the declarations of 2 modules: AppModule and IdentityRegistryModule! Please consider moving IconSpacerDirective to a higher module that imports AppModule and IdentityRegistryModule. You can also create a new NgModule that exports and includes IconSpacerDirective then import that NgModule in AppModule and IdentityRegistryModule.

Here is my identityRegistryModule:
import { IconSpacerDirective } from '../shared/custom-directive/icon-spacer.directive';
@NgModule({
  declarations: [
    IconSpacerDirective
  ],
  imports: [
    IdentityRegistryRoutingModule,
    MaterialModule

  ],
  providers: [
    IdentityService,
  ],
})
export class IdentityRegistryModule { }

my app.module.ts as follows:
import { IconSpacerDirective } from './shared/custom-directive/icon-spacer.directive';

@NgModule({
  declarations: [
    AppComponent,
    MainNavComponent,
    SideNavComponent,
    HeaderComponent,
    HomeComponent,
    IconSpacerDirective,

  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    FlexLayoutModule,
    BrowserAnimationsModule,
    LayoutModule,
    MaterialModule,
    OAuthModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent],
  //exports: [IconSpacerDirective]
})
export class AppModule { }

How can i use the IconSpacerDirective inside my identityRegistryModule

A: If you want to use the IconSpacerDirective in both the AppModule and the IdentityRegistryModule, then you need to create a separate module for that directive that you can then import in the modules where you need it.
@NgModule({
  declarations: [IconSpacerDirective],
  exports: [IconSpacerDirective]
})
export class IconSpacerModule { }

@NgModule({
  imports: [IconSpacerModule]
})
export class AppModule { }

@NgModule({
  imports: [IconSpacerModule]
})
export class IdentityRegistryModule { }

A: Since you are importing the module you don't need to explicitly declare it again. Remove it from the declarations of IdentityRegistryModule as that is what the error clearly states.
In the app.module, export the IconSpacerDirective
@NgModule({
  ...
  exports: [IconSpacerDirective] // so that it can be used when this module is imported
})
export class AppModule { }

and import the app.module in identityRegistryModule
@NgModule({
  imports: [
    IdentityRegistryRoutingModule,
    MaterialModule,
    AppModule
  ]
  ...
})
export class IdentityRegistryModule { }

A: if you want to use the directive only in IdentityModule then no need to add it in App.module. Declare it in Identity module and use it. But if you want to use the directive in multiple modules including components in app.module then create separate module for common directives like:
common directive module
@NgModule({
 declarations: [IconSpacerDirective],
 exports:[IconSpacerDirective]
})
export class MyCommonModule{}

Then export it where ever you want. Lets suppose you want to use it for the component in app.module as well component in Identity module the follow below logic:
app.module.ts
@NgModule({
imports: [MyCommonModule]
})

identiyt.module.ts
import { IconSpacerDirective } from '../shared/custom-directive/icon-spacer.directive';
@NgModule({
  imports: [
    IdentityRegistryRoutingModule,
    MaterialModule,
    **MyCommonModule**
  ],
  providers: [
    IdentityService,
  ],
})
export class IdentityRegistryModule { }


text:
Q: Flutter Firestore Get a stream of each entry out of a map I have stored a map in Firestore.
Now I would like to receive a stream for every single entry (training) in this map.
Is there a possible way to do this.

Maybe like in the following, but here my stream just contains 1 Future, because of one document:
    Stream<CalendarEvent> getTrainings() {
      return _firestore
        .collection('users')
        .doc('${_authentication.getUID()}')
        .collection('user')
        .doc('trainings')
        .snapshots()
        .map((doc) => CalendarEvent.fromJson(doc.data()));
    }

Here is the code of CalendarEvent where a use the factory constructor to generate instances of calendar event,
        class CalendarEvent {
          final String title;
          final String id;
          final String date;

          CalendarEvent({this.title, this.id, this.date});

          Map<String, dynamic> toMap() {
            Map<String, dynamic> map = {
              'title': title,
              'id': id,
              'date': date,
            };
          }

          //Here we generate user object out of firestore
          factory CalendarEvent.fromJson(Map<dynamic, dynamic> json) {
            return CalendarEvent(
              title: 'null',
              id: 'null',
              date:'null'
            );
          }

        }

Thanks in advance.

A: You need to actually get the trainings map from the document snapshot and then map that into a Stream of List like below:
Stream<List<CalendarEvent>> getTrainings() {
  return _firestore
      .collection('users')
      .doc('${_authentication.getUID()}')
      .collection('user')
      .doc('trainings')
      .snapshots()
      .map((doc) {
    Map<String, dynamic> trainingsMap = doc.data()['trainings'];
    return trainingsMap.entries.map((mapEntry) {
      Map<String, dynamic> json = {'id': mapEntry.key, ...mapEntry.value};

      return CalendarEvent.fromJson(json);
    }).toList();
  });
}

And update your CalendarEvent.fromJson to this:
factory CalendarEvent.fromJson(Map<dynamic, dynamic> json) {
  return CalendarEvent(
    title: json['trainingsName'],
    id: json['id'],
    date: json['trainingsDate']
  );
}


text:
Q: Block dispatch_queue until it sends the entire data I am trying to send some hexadecimal packets that create a waveform at the server side in objective c by creating a tcp/ip connection.My problem is that i am able to send the data and can also see the waveform at the server side.But what happens is that due to network delays sometimes the waveform seens to be overlapped(the reason is the server tries to sync the packets every after 5 minutes). My question here is basically how to send the packets to the server in such a way that until the packets are synced i dont send another packket to the server
    dispatch_queue_t connectionTest=dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);
                    dispatch_async(connectionTest, ^{
                    if(outputStream)
                    {

                        NSInteger sizeOfPacket=13;
                        unsigned char myPacket[13];
                        unsigned char crcCal=0;
                        myPacket[0]=START_OF_HEADER;
                        myPacket[1]=START_OF_TEXT;
                        myPacket[2]=8;
                        myPacket[3]=0x6a;
                        myPacket[4]=0x06;
                        myPacket[5]=0x80;
                        myPacket[6]=Some value;//
                        myPacket[7]=0x80;
                        myPacket[8]=Some value;//
                        myPacket[9]=0x54;//changed 54 to 50
                        myPacket[10]=0x04;
                        for (int j=3;j<myPacket[2]+3;j++)
                        {
                            crcCal=crcTable[crcCal^myPacket[j]];
                        }
                        myPacket[11]=crcCal;
                        myPacket[12]=END_OF_TEXT;

                        NSLog(@"crc value is %c",crcCal);

                        NSData* dataPacket = [NSData dataWithBytes:(const void *)myPacket length:sizeof(unsigned char)*sizeOfPacket];
                        [outputStream write:[dataPacket bytes] maxLength:[dataPacket length]];

                    }
                    });

A: One approach might be to dispatch_suspend the outgoing queue from within the block where you send a packet, and then dispatch_resume the outgoing queue from whatever code receives the acknowledgment from the server.


text:
Q: Send BroadcastReceiver data in Activity to a Dialog as it comes in I have an Activity where I'm receiving some string data through Bluetooth. I need to send this data to a dialog which is already opened as it comes from Bluetooth.
//Getting Bluetooth data from the receiver
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String data = intent.getStringExtra("Status");

            //I need to send data from here to a dialog

        }
    }
};

and my Dialog is normal DialogFragment
Data will be coming counties through Broadcast and I need to get it in Dialog.
Thanks in Advance.

A: You need to check top visible fragment if its your dialog fragment then you need to pass your data into your dialog fragment:-
// this code inside your onReceive()
String data = intent.getStringExtra("Status");
Fragment fragment = getTopVisibleFragment(getSupportFragmentManager(),R.id.fragment_container);
if (fragment != null && fragment instanceof DialogFragment) {
      fragment.setData(data);
}

public static Fragment getTopVisibleFragment (FragmentManager manager, int containerId) {
    return manager.findFragmentById(containerId);
}


text:
Q: Image wont upload mysqli So i have this upload file, that upload images into a database. I haven't worked with Mysqli for that long so i dont know if i'm doing something wrong?
Database table (cover): id (int 11), username (varchar 400), image (longblob).
<form action="insertimg.php" method="post" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="submit" name="submit" id="submit" value="Submit Picture" />
</form>

This is the upload file:
$name = $_SESSION['Band_name'];

$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if(substr($imageType,0,5) == "image"){

$query = "INSERT INTO cover VALUES ('', '$name', '$imageData')";

$db->query($query) or die('Error, query failed');
}

A: Adding addslashes around file_get_contents() made it work.


text:
Q: Tray icon problem in xfce and gnome with any icon theme On the GNOME and xfce4 desktops tray icon's do not show applications status correctly. for example when obs-studio Records the desktop or is in pause mode No symbols are displayed on the obs tray icon.
When i use linux default icons theme like : Adwaita or Breeze everything is fine BUT i wanna install another popular icon themes like arc , papirus , paper and ... :

I traied many ways but This problem seems to be related to icon themes or DE !
I tested on Gnome 41 and xfce4.
Can I use special theme only for tray that are separate from the theme icons of the entire system ? for example papirus for all desktop icons and Adwaita for only tray icons ???


text:
Q: Find a line of a file, extract part of it and replace in the same place in Bash I have a large file with the following content (this is an extract of it):
Total execution time (hh:mm:ss.ms): 00:00:8,4880 (8488 mseconds)
Error  0.00044
Stage 1 execution time (hh:mm:ss.ms): 00:00:7,0430 (7043 mseconds)
Stage 2 execution time (hh:mm:ss.ms): 00:00:1,4450 (1445 mseconds)
Total execution time (hh:mm:ss.ms): 00:00:0,0170 (17 mseconds)
Number of variables   6

Those lines could be more than one time and with different values. I would like to replace for the mseconds value. So, the expected output is:
8488
Error  0.00044
7043
1445
17
Number of variables   6

I've tried this but I don't know how can I replace the extracted value in the line:
grep "Total execution time (hh:mm:ss.ms):" file.txt | cut -d " " -f6 | cut -d "(" -f2

And I also was thinking doing this for each case (Total, Stage 1 and Stage 2), but if there is something more practical I would be very grateful.

A: It would be easier using sed (I use GNU sed, to be specific) to achieve the result:
sed -E '/execution time/s/.*\(([0-9]*) mseconds\)/\1/'

Keep only the digit part \(([0-9]*) mseconds\) in lines with pattern execution time. The ([0-9]*) are used as backreference in order to output the desired number by using \1, and \( and \) mean literal parenthesis.

A: Could you  please try following.
awk '
/execution time/ && match($0,/[0-9]+ mseconds/){
  val=substr($0,RSTART,RLENGTH)
  sub(/ [a-zA-Z]+/,"",val)
  print val
  val=""
  next
}
1
'  Input_file


text:
Q: My state is using it's initial values and not those that were set when the page loaded when called from a component Problem
I have a "Calendar" component that when a day is click, it calls a function in it's parent (props). The whole day being clicked thing is not important as I've stripped a lot of the code to try to figure out where my issue is.
Within the parent, I have it run a function that console.logs a state. However, it uses the state's initial values and not the values that were set. Using a button I setup below the calendar (which calls the same function) results in the correct data however. Thus I know the data is being loaded and setted from my database.
Expected Result
Clicking a day on the calendar which calls a console.log function should display the state's values that were set when the page loaded.
Actual Result
The state that is console.log is using values from when it was initially created, not the values that were set.
Things I've done
Originally, the BookPage.js (the "parent" file) had a lot more code but I stripped it down until I found the issue had to do with the calendar component I made. To make sure that the issue wasn't related to my database, I added the Button below the calendar which called the same function as the calendar. Clicking the button results in the correct values being displayed.

This is my page
import { Colors, Styles } from "./GlobalStyles";
import {
  Button,
  Grid,
  TextField,
  Box,
  Tooltip,
  SvgIcon,
  Slider,
} from "@material-ui/core";
import {
  English,
  French,
  Spanish,
  Tagalog,
  Chinese,
  Korean,
  Arabic,
  Hindi,
} from "../Strings";
import moment from "moment";
import Calender from "./components/calender";

const BookPage = (props) => {
  const initialState = {
    expert: null,
    availability: [
      [1, 24],
      [1, 24],
      [1, 24],
      [1, 24],
      [1, 24],
      [1, 24],
      [1, 24],
    ],
  };
  const reducer = (state, newState) => ({ ...state, ...newState });
  const [state, setState] = useReducer(reducer, initialState);

  useEffect(() => {
    LoadExpertData();
  }, []);

  // Loads the expert's data
  const LoadExpertData = async () => {
    await props.firestore
      .collection("expertData")
      .where("userID", "==", props.bookID)
      .get()
      .then((loadedData) => {
        setState({
          availability: [
            [
              loadedData.docs[0].data().availability.availability.sun[0],
              loadedData.docs[0].data().availability.availability.sun[1],
            ],
            [
              loadedData.docs[0].data().availability.availability.mon[0],
              loadedData.docs[0].data().availability.availability.mon[1],
            ],
            [
              loadedData.docs[0].data().availability.availability.tue[0],
              loadedData.docs[0].data().availability.availability.tue[1],
            ],
            [
              loadedData.docs[0].data().availability.availability.wed[0],
              loadedData.docs[0].data().availability.availability.wed[1],
            ],
            [
              loadedData.docs[0].data().availability.availability.thu[0],
              loadedData.docs[0].data().availability.availability.thu[1],
            ],
            [
              loadedData.docs[0].data().availability.availability.fri[0],
              loadedData.docs[0].data().availability.availability.fri[1],
            ],
            [
              loadedData.docs[0].data().availability.availability.sat[0],
              loadedData.docs[0].data().availability.availability.sat[1],
            ],
          ],
        });
      });
  };

  const alertData = () => {
    console.log(state.availability);
  };

  return (

      <Calender language={props.language} ReturnDay={(d) => alertData()} />
      <Button onClick={() => alertData()}>BUTTON</Button>

  );
};

export default BookPage;

This is the Calender
import React, { useReducer, useEffect } from "react";
import { Colors, Styles } from "../GlobalStyles";
import {
  Button,
  Grid,
  TextField,
  Box,
  Tooltip,
  SvgIcon,
  Select,
  MenuItem,
} from "@material-ui/core";
import moment from "moment";
import { English, French, Spanish } from "../../Strings";
const Calender = (props) => {
  const initialState = {
    dateObject: moment(),
    weekdayshort: moment.weekdaysShort(),
    blankDays: [],
    yearLimit: [2020, 2021, 2022, 2023],
    month: 0,
    year: 2020,
  };

  const reducer = (state, newState) => ({ ...state, ...newState });
  const [state, setState] = useReducer(reducer, initialState);

  useEffect(() => {
    GenerateCalender(null, null);
  }, []);

  // Finds the first day of the month
  const GenerateCalender = (m, y) => {
    if (m !== null && y !== null) {
      state.dateObject.month(m);
      state.dateObject.year(y);
    } else {
      setState({
        month: state.dateObject.month(),
        year: state.dateObject.year(),
      });
    }
    var firstDay = moment(state.dateObject).startOf("month").format("d");

    // Empty days
    var emptyDay = [];
    for (let i = 0; i < firstDay; i++) {
      emptyDay.push({""}	);
    }
    // Actual Days
    let actualDays = [];
    for (let i = 1; i <= state.dateObject.daysInMonth(); i++) {
      actualDays.push(

            props.ReturnDay({
              month: state.dateObject.month(),
              day: i,
              year: state.dateObject.year(),
            })
          }
        >
          {i}

      );
    }

    var days = [...emptyDay, ...actualDays];
    let rows = [];
    let cells = [];

    days.forEach((row, i) => {
      if (i % 7 !== 0) {
        cells.push(row);
      } else {
        rows.push(cells);
        cells = [];
        cells.push(row);
      }
      if (i === days.length - 1) {
        rows.push(cells);
      }
    });

    setState({
      calender: rows.map((d, i) => {
        return
{d}
;
      }),
    });
  };

  const ChangeYear = (year) => {
    GenerateCalender(state.month, year);
    setState({ year: year });
  };

  const ChangeMonth = (month) => {
    GenerateCalender(month, state.year);
    setState({ month: month });
  };

  return (

      <Select
        value={state.month}
        onChange={(e) => {
          ChangeMonth(e.target.value);
        }}
        style={{ width: 150 }}
      >
        {props.language.Calender.Months.map((m, v) => (
          <MenuItem value={v}>{m}</MenuItem>
        ))}
      </Select>

      <Select
        value={state.year}
        onChange={(e) => {
          ChangeYear(e.target.value);
        }}
        style={{ width: 150 }}
      >
        {state.yearLimit.map((y) => (
          <MenuItem value={y}>{y}</MenuItem>
        ))}
      </Select>

      {props.language.Calender.Months[state.dateObject.month()]}
      {state.dateObject.year()}

              {props.language.Calender.DaysShort[0]}

              {props.language.Calender.DaysShort[1]}

              {props.language.Calender.DaysShort[2]}

              {props.language.Calender.DaysShort[3]}

              {props.language.Calender.DaysShort[4]}

              {props.language.Calender.DaysShort[5]}

              {props.language.Calender.DaysShort[6]}

{state.calender}

  );
};

const LocalStyles = {
  calSlot: {
    width: 60,
    margin: 5,
  },
  clickableDay: {
    width: 60,
    margin: 5,
    cursor: "pointer",
  },
};

export default Calender;

Here, I have a screenshot of part of the page. I have the calendar and a button. On the right of the image is the result of both scenarios. The top is if a day on the calendar is clicked, it results in the state's initial values being used. The bottom is if the button is clicked, it results in the proper values that were loaded. Both call the same function that console.log the state.

A: I feel like there is something fundamental I'm not understanding with the whole component lifecycle, but you could try useCallback:
const alertData = React.useCallback(
  () => console.log(state.availability),
  [state.availability]
);


text:
Q: Maintaining timecode using -ss trim tool I'm currently using this FFMPEG script (using "run shell script" in Automator) on QT ProRes files to strip off the first six channels of audio, pass through for audio and video, and trim the first 6.5 seconds off the beginning of the video:
for f in "$@"
do
/usr/local/bin/ffmpeg -ss 6.5 -i "$f" -c:v copy -map 0:0 -c:a copy -map 0:7  "${f%.*}_ST.mov"
done

When I use this script, it successfully trims the file but then moves the original timecode up to the new beginning of the clip. So if 00:59:48:00 was my timecode at the beginning of the original clip, it's now also the starting timecode of the beginning of my trimmed clip.
My question is how can I trim 6.5 seconds off the beginning while also trimming that same amount of time off my timecode as well?
So instead of my trimmed clip (let's say 23.98 fps) starting at 00:59:48:00, it would start at 00:59:54:12 since 6.5 seconds (roughly 156 frames) have been trimmed.

A: A manual way to do this is via
ffmpeg -ss 6.5 -i "$f" -c:v copy -map 0:0 -timecode 01:23:45:30 -c:a copy -map 0:7  "${f%.*}_ST.mov"

Don't see an automatic way to do this. There is a copyts option but that relates to the video packets, not the ancillary timecode track.


text:
Q: How do I install SIP makefile to use PyQt? I want to install sip to use with PyQt.

*

*I've unpacked the sip download

*I ran Windows command prompt and changed dir to C:\Python\sip\

*I ran the configure.py script, I did try the python configure.py first but because I unpacked the sip folder into C:\Python I couldn't get command line to recognise the python shell

*This returned the makefile in command prompt, i couldn't then use make, it just gave me the error 'make' is not recognized

*I looked into it and thought i would solve this by using minGW

*Now my command prompt shows:
C:\Python\sip>configure.py --platform win32-g++
This is SIP 4.17 for Python 2.7.11 on win32.
The SIP code generator will be installed in C:\Python27.
The sip module will be installed in C:\Python27\Lib\site-packages.
The sip.h header file will be installed in C:\Python27\include.
The default directory to install .sip files in is C:\Python27\sip.
Creating siplib\sip.h...
Creating siplib\siplib.c...
Creating siplib\siplib.sbf...
Creating sipconfig.py...
Creating top level Makefile...
Creating sip code generator Makefile...
Creating sip module Makefile...

*I then run make and i get
C:\Python\sip>make
'make' is not recognized as an internal or external command,
operable program or batch file.
I've searched through Stack and some are close to the answer but nothing has got me quite there yet.
I'm looking into downloading visual studio as I have been reading that your supposed to run the makefile from there on windows.
Is this correct or am I looking in the wrong place?

A: So I've found the correct way to use make. I had to set my path to include mnGW and use: mingw32-make and mingw32-make install
I found this ironically on the python wiki!
https://wiki.python.org/moin/BuildPyQt4Windows


text:
Q: ./bootstrap: 17: exec: autoreconf: not found : OpenTSDB installation I am trying to install OpenTSDB on Ubuntu, and I am following this documentation. But after running these commands:
git clone git://github.com/OpenTSDB/opentsdb.git
cd opentsdb

running this commanding is giving the following console output:
./build.sh

Console Output:
seed-admin@seedadmin-Inspiron-3847:~/Abharthan/opentsdb$ sudo ./build.sh
+ test -f configure
+ ./bootstrap
./bootstrap: 17: exec: autoreconf: not found

What is the problem?

A: sudo apt-get install autoconf solved my problem


text:
Q: How can i modify code to spawn enemies every 30 seconds only if there is less than 10 enemies How can i modify code on unity c# to spawn enemies every 30 seconds only if there is less than 10 enemies on the field.
At the moment i have a while loop inside an enumerator that spawns enemies to 10 but is only called in the beginning, i need the function to spawn enemies, when the amount of enemies reaches 1.
Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GenerateEnemies : MonoBehaviour
{
    public GameObject theEnemy;
    public int xPos;
    public int zPos;
    public int enemyCount;

    void Start()
    {
        StartCoroutine(SpawnEnemy());
    }

    IEnumerator SpawnEnemy()
    {
        while (enemyCount < 10)
        {
            xPos = Random.Range(153, 203);
            zPos = Random.Range(-76, 76);
            Instantiate(theEnemy, new Vector3(xPos, 9, zPos), Quaternion.identity);
            yield return new WaitForSeconds(0.9f);
            enemyCount += 1;
        }
    }
}

A: I haven't tested this code at all
Hi Obito, let me show you this code and see if you can implement it:
[Header("Spawning Properties")]
public GameObject enemyPrefab;
public Vector3 spawnPoint;
public int maxEnemies = 10;
public int minEnemies = 1;

//This is the time between each spawn.
public float spawnDelay = 0.9f;
public spawnTimer = 30f;
//Every enemy *needs* an 'Enemy' script, or tag, to identify what is an enemy.
public int EnemyCount => GameObject.FindObjectsOfType<Enemy>();

private void Awake()
{
    spawnTimer = 30f;
}

private void Update()
{
    spawnTimer -= Time.deltaTime;
    //"Do I need to start spawning enemies?"
    if(EnemyCount <= minEnemies && spawnTimer <= 0) {
        StartCoroutine(SpawnEnemies());
    }
}

private IEnumerator SpawnEnemies()
{
    while(EnemyCount <= maxEnemies)
    {
        Instantiate(enemyPrefab, spawnPoint, Quaternion.identity);
        yield return new WaitForSeconds(spawnDelay);
        Debug.Log("Enemy " + EnemyCount + "/" + maxEnemies + " spawned.");

    }
    spawnTimer = 30f;
}

Tip: If you want to make a "enemies per wave" system, you should try doing this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Spawning Properties")]
    public GameObject enemyPrefab;
    public Vector3 spawnPoint;
    public int[] wavesCount = { 10, 14, 23, 40 };
    public int minEnemiesPerWave = 1;
    public int currentWave = 0;
    //This is the time between each spawn.
    public float spawnDelay = 0.9f;
    private float spawnTimer = 30f;
    //Every enemy *needs* an 'Enemy' script, or tag, to identify what is an enemy.
    public int EnemyCount => GameObject.FindObjectsOfType<Enemy>();

    private void Start() {
        spawnTimer = 30f;
    }

    private void Update()
    {
        spawnTimer -= Time.deltaTime;
        //"Do I need to start spawning enemies?"
        if(EnemyCount <= minEnemiesPerWave && spawnTimer <= 0) {
            StartCoroutine(SpawnEnemies());
        }
    }

    private IEnumerator SpawnEnemies()
    {
        while(EnemyCount <= wavesCount[currentWave])
        {
            Instantiate(enemyPrefab, spawnPoint, Quaternion.identity);
            yield return new WaitForSeconds(spawnDelay);
            Debug.Log("Enemy " + EnemyCount + "/" + maxEnemies + " spawned.");
        }
        spawnTimer = 30f;
        currentWave++;
    }
}

A: Simply wrap your code in an endless loop and do e.g.
public class GenerateEnemies : MonoBehaviour
{
    public GameObject theEnemy;
    public int xPos;
    public int zPos;
    public int enemyCount;

    IEnumerator Start()
    {
        // As long as you yield within this is totally fine in an IEnumerator
        while(true)
        {
            // If there is already 10 or more
            if(enemyCount >= 10)
            {
                // wait a frame and check again
                yield return null;
                continue;
            }

            xPos = Random.Range(153, 203);
            zPos = Random.Range(-76, 76);
            Instantiate(theEnemy, new Vector3(xPos, 9, zPos), Quaternion.identity);
            enemyCount++;
            // waiting 30 seconds then check again
            yield return new WaitForSeconds(30);
        }
    }
}

Assuming of course that enemyCount is somewhere reduced from the outside.
Or from what you say you wan to additionally wait until the amount reaches 1 and then start spawning again so you could add
...
enemyCount++;
if(enemyCount >= 10)
{
    yield return new WaitUntil(() => enemyCount <= 1);
}
else
{
    yield return new WaitForSeconds(30);
}
...

So you wait 30 seconds between spawning enemies but once you reach 10 enemies you wait until the amount is again reaching 1 or less


text:
Q: How can I reaccess a terminal window that has disappeared when its deselected (focus is lost)? Today, suddenly after executing a terminal window and starting my script, it disappeared! there is no terminal icon on the ubuntu toolbar, and I cant access the terminal using Alt-Tab.

I can create new terminal windows using dash, but I cant access them when I minimize them, once minimized they are no more accessible!

minimized one of the terminals, its no where to be found!

I noticed its not only minimizing that makes them disappear! if I click on any program so that the focus is lost (for example If I open my browser, or sublime editor, or even navigate to one of my drives,opening a folder, etc, the terminal window will disappear !)


text:
Q: If I change the domain of my site, what happens with the cookies? We have a site where we are using cookies for tracking purposes. Now we are thinking in changing the domain of our site but we will want to still recognise User's sessions from the old domain. Is this possible?

A: You can't retrieve cookies that belong to other domains. As a workaround (in case you can still use the old domain); by creating an iframe inside http://newdomain.com from http://olddomain.com, you can get cookies and send to parent via postMessage.

A: Cookies are affected by same origin policy but you can bypass it with CORS (Cross-origin resource sharing).
CORS is a play between browser and server.
Basic idea is allow ajax request to cross domains but you can use to share cookies(security measures should be taken).
Browser send a request with Origin header.
If the server allows the request then it reply with Access-Control-Allow-Origin header with the value of origin.
If the server doesn't reply with the header or don't match Origin with  Access-Control-Allow-Origin browser disallow the request.
But it doesn't send cookies or something like that by default(you have to add "allow-credentials" extra header).
With CORS you can share the session between domains adding to new domain server the following headers:
Access-Control-Allow-Origin: https://original-domain.com
Access-Control-Allow-Credentials: true

More info about CORS:

*

*https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

*http://quickleft.com/blog/cookies-with-my-cors


text:
Q: Angular filter array of an array For the past few days I have had difficulties with filtering an array of array with Angular and displaying it. I have tried searching for similar posts but I could not find solution for my case.
Example how my data looks:
$scope.answers = [
    {title: "Qestion1", keywords: ["dino", "dog", "cat"]},
    {title: "Quessstion2", keywords: ["cat", "dog"]}
];

Currently I am displaying a list:
<div class="solution-box" ng-repeat="answer in pagedItems[currentPage]">

I have two search fields:
<input type="text" ng-model="title"  ng-change="search1()"  class="form-control" placeholder="Filter by title">
<input type="text" ng-model="keys"  ng-change="search2()" class="form-control" placeholder="Filter by keywords">

Search1() function which just works fine:
$scope.search1 = function () {
     $scope.filteredItems = $filter('filter')($scope.answers, function (answer) {
         if (searchMatch(answer.title, $scope.title))
             return true;
         return false;
     });
     $scope.currentPage = 0;
     // now group by pages
     $scope.groupToPages();
 };

Search2() function which does not alter filteredItems
$scope.search2 = function () {
        $scope.filteredItems = $filter('filter')($scope.answers, function (answer) {
            return $filter('filter')(answer.keywords, function (keyword) {
                if (searchMatch(keyword, $scope.keys)) {
                    console.log($scope.filteredItems + '/' + keyword + '|' + $scope.keys);
                    return true;
                }
                return false;
            });
        });
        $scope.currentPage = 0;
        // now group by pages
        $scope.groupToPages();
    };

Could anyone please give tips what could be wrong in Search2() function?
While I am logging filteredItems, it logs me correct amount of answers, but the list still remains of the same size as it was.
What is the main logic of custom filters that I am missing here?
Thanks,

A: As @mgilson pointed out you need to return a boolean from the filter callback function but you are returning an array which will always be truthy. There is also no need to use $filter('filter') here. You could just do something like this:
$scope.filteredItems = $scope.answers.filter(function(answer) {
    var matches = answer.keywords.filter(function() {
        return searchMatch(keyword, $scope.keys);
    });
    return matches.length > 0;
});


text:
Q: Animating with a for loop part 2 I have another question thats has been bugging me. It's kinda a follow up from my other question "Animating with a for loop?" Ok so I have that down, but how could I animate each ball to go randomly around the stage and not follow each other?
Here is my code:
ball is pulled from an external class named Ball.
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.text.TextField;
    import flash.ui.Keyboard;

    public class Dummy extends Sprite
    {

        private var balls:Array;
        private var ball:Ball;
        private var ballNum: Number = 10;

        private var ax:Number = 4;

        public function Dummy()
        {
            init();
        }
        private function init():void
        {
            balls = new Array();
            for(var i:Number = 0; i < ballNum; i++)
            {
                ball = new Ball(Math.random() * 30);
                ball.x = Math.random() * stage.stageWidth;
                ball.y = Math.random() * stage.stageHeight;
                addChild(ball);

                balls.push(ball);
            }
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        protected function onEnterFrame(event:Event):void
        {
            for(var i:int = 0; i < balls.length; i++)
            {
                balls[i].x += ax;
            }
        }
    }
}

A: Give each ball object a different direction and use that to move the ball instead of the ax value.
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.text.TextField;
    import flash.ui.Keyboard;

    public class Dummy extends Sprite
    {

        private var balls:Array;
        private var ball:Ball;
        private var ballNum: Number = 10;

        private var directions:Array = [new Point(-1,-1),new Point(0,-1),new Point(1,-1),
                                new Point(-1,0),new Point(1,0),
                                new Point(-1,1),new Point(0,1),new Point(1,1)];

        public function Dummy()
        {
            init();
        }
        private function init():void
        {
            balls = new Array();

            for(var i:Number = 0; i < ballNum; i++)
            {
                ball = new Ball(Math.random() * 30);
                ball.x = Math.random() * stage.stageWidth;
                ball.y = Math.random() * stage.stageHeight;
                ball.direction = directions[Math.floor(Math.random()*directions.length)];
                addChild(ball);

                balls.push(ball);
            }
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        protected function onEnterFrame(event:Event):void
        {
            for(var i:int = 0; i < balls.length; i++)
            {
                balls[i].x += balls[i].direction.x;
                balls[i].y += balls[i].direction.y;
            }
        }
    }
}

A: Give your Ball class properties for speed, and a method move() that will adjust their respective coordinates, and probably will be enhanced to check for collisions sometimes later, so that your balls could rebound of walls for example.
// Ball class additions follow
private var vx:Number;
private var vy:Number;
public function Ball() {
    // ... original constructor here
    var angle:Number=Math.random(2.0*Math.PI); // random angle
    var vel:Number= MAX_VELOCITY*(0.5+0.5*Math.random()); // random velocity module
    // define this constant^
    vx=vel*Math.cos(angle);
    vy=vel*Math.sin(angle); // composites of velocity
}
public function move():void {
    this.x+=vx;
    this.y+=vy;
}

// main class
    protected function onEnterFrame(event:Event):void
    {
        for(var i:int = 0; i < balls.length; i++)
        {
            balls[i].move();
        }
    }


text:
Q: map icon attribute popups I have a code that plots points on a map for an Json file. I would like to have a pop up menu with some of the other attibutes in the json file when icon is clicked. I tried several examples but can seem to get it right
    $(window).load(function() {
  var center = new google.maps.LatLng(40.679, -73.866);
  var mapOptions = {
    zoom: 9.5,
    center: center
  }
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  const iconBase =
    "https://drive.google.com/drive/folders/1tjeBTcvIukQGv7JfGKS_zpQvkSJbHDHZ?usp=sharing";

  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = () => {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      proj4.defs("EPSG:2263", "+proj=lcc +lat_1=41.03333333333333 +lat_2=40.66666666666666 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000.0000000001 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=us-ft +no_defs");
      var source = new proj4.Proj('EPSG:2263');
      var dest = new proj4.Proj('EPSG:4326');
      const res = JSON.parse(xhr.responseText);

      Object.entries(res).forEach((entry) => {
        if (entry[1]["sign_x_coord"] != undefined && entry[1]["sign_y_coord"] != undefined) {
          var signdescription = entry[1]['sign_description']
          var x = parseFloat(entry[1]['sign_x_coord']);
          var y = parseFloat(entry[1]['sign_y_coord']);
          var p = new proj4.toPoint([x, y]);

          var new_p = proj4.transform(source, dest, p);
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(new_p.y, new_p.x),
            icon: "http://maps.google.com/mapfiles/kml/pal4/icon7.png",
            title: signdescription
          });
          marker.setMap(map);

        }
      });

    }
  };
  data_url = "https://data.cityofnewyork.us/resource/afgb-4qw7.json?$$app_token=m7Vxfi5fAnxoowHlFBmTuYsBw";
  xhr.open('GET', data_url, true);
  xhr.setRequestHeader('Accept', 'application/json');
  xhr.send(null);
});


text:
Q: am trying to implement search bar in my app so that i can search the objects which are retrieved from parse.com  import UIKit

 class MasterTableViewController: UITableViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate {

@IBOutlet var searchBar: UISearchBar!

// creating array for holding ojects

var noteObjects: NSMutableArray! = NSMutableArray()
  var v = 0

var searchActive : Bool = false
var data:[PFObject]!
var filtered:[PFObject]!

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.delegate = self

}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    if v == 0 {
        self.fetchAllObjectsFromLocalDataStore()
        //self.fetchAllObjects()

    }
}

// fetching data from local datastrore and from parse

func fetchAllObjectsFromLocalDataStore(){

    let query: PFQuery = PFQuery(className: "className")
    query.orderByDescending("createdAt")

    query.fromLocalDatastore()

    query.findObjectsInBackgroundWithBlock { (var objects, error) -> Void in
        self.search()
        if (error == nil) {

            let temp: NSArray = objects as! NSArray

            self.noteObjects = temp.mutableCopy() as! NSMutableArray
           self.search()
             self.tableView.reloadData()

        }else {
        print(error!.userInfo)

        }
    }

}

func fetchAllObjects(){

   let query: PFQuery = PFQuery(className: "className")
    query.orderByDescending("createdAt")

  search()
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if (error == nil) {

            PFObject.pinAllInBackground(objects, block:  nil )

            self.fetchAllObjectsFromLocalDataStore()

           // self.tableView.reloadData()

        } else {
        print(error?.userInfo)

        }
 }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

    return self.noteObjects.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MasterTableViewCell

 let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject

    cell.MasterTitleLabel?.text = object["Title"] as? String
    cell.MasterTextLabel.text = object["Fstory"] as? String
    cell.MasterTimeLabel.text = object["Time"] as? String
    cell.MasterLocationLabel.text = object["Location"] as? String

    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("openStory", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let upcoming: AddNoteTableViewController = segue.destinationViewController as! AddNoteTableViewController

    if (segue.identifier == "openStory"){

        let indexPath = self.tableView.indexPathForSelectedRow!

        let object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject

        upcoming.object = object

        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

}

@IBAction func btnReload(sender: AnyObject) {

    fetchAllObjects()
  }

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
  }
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete ){

        let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        // the below for deleting the selected cell's object from server's database
       // object.deleteInBackground()

        //the below for deleting the selected cell's object from localstorage
        object.unpinInBackground()

      self.noteObjects.removeObjectAtIndex(indexPath.row)
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

  }
}

func search(searchText: String? = nil){
    let query = PFQuery(className: "className")
    if(searchText != nil){
        query.whereKey("Title", containsString: searchText)
    }
    query.findObjectsInBackgroundWithBlock { (results, error) -> Void in
        self.data = results! as [PFObject]
        self.tableView.reloadData()
    }
}

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

}
the above code is for retrieving parse's objects and for implementing the search bar so that i can search my objects via search function but i don't what am missing or how to it properly if anybody knows than please help me

A: you can try something like this using UIsearchBar
class TableViewController: UITableViewController, UISearchBarDelegate {

 @IBOutlet var searchBar: UISearchBar!
 var userList:NSMutableArray = NSMutableArray()

var noteObjects: NSMutableArray = NSMutableArray()

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.delegate = self

        self.fetchAllObjectsFromLocalDataStore()

}

func loadUsers(name:String){
    var findUsers:PFQuery = PFUser.query()!

    if !name.isEmpty{
        findUsers.whereKey("username", containsString: name)
        findUsers.whereKey("username", containsString: name .lowercaseString)

        let user = PFUser.currentUser()

        if let user = PFUser.currentUser() {
            findUsers.whereKey("institute", equalTo: user["institute"])
        }
    }
           findUsers.fromLocalDatastore()

  findUsers.findObjectsInBackgroundWithBlock { ( objects, error) -> Void in

                if (error == nil) {

                               self.userList = NSMutableArray(array: objects!)

                                 self.tableView.reloadData()
             }else {
                    print(error!.userInfo)

   }
    }}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    loadUsers(searchText)
 self.searchBar.setShowsCancelButton(true, animated: true)

}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    loadUsers("")

    self.searchBar.setShowsCancelButton(false, animated: true)
    self.searchBar.endEditing(true)
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

      if searchBar.text == "" {

    return noteObjects.count
    } else {

        return userList.count }
        //self.noteObjects.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UsersTableViewCell

    if searchBar.text == "" {

    let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        let photo: PFFile = object["photo"] as! PFFile

        photo.getDataInBackgroundWithBlock{
            (imageData:NSData?, error:NSError?)-> Void in

            if (error == nil){
                let image:UIImage = UIImage(data: imageData!)!
                cell.imgViewUser.image = image
            }
            else if error != nil{
                print("error")
            }
         }

        cell.lblUserInterest.text = object["interest"] as? String
        //cell.imgViewUser.image = object["photo"]  as? PFFile
        cell.lblUsername.text  = object["username"] as? String
      return cell
    } else  {

    let object : PFObject = self.userList.objectAtIndex(indexPath.row) as! PFObject

    let photo: PFFile = object["photo"] as! PFFile

    photo.getDataInBackgroundWithBlock{
        (imageData:NSData?, error:NSError?)-> Void in

        if (error == nil){
            let image:UIImage = UIImage(data: imageData!)!
            cell.imgViewUser.image = image
        }
        else if error != nil{
            print("error")
        }}
      cell.lblUserInterest.text = object["interest"] as? String
    //cell.imgViewUser.image = object["photo"]  as? PFFile

    cell.lblUsername.text  = object["username"] as? String

  return cell
    }

}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var object :AnyObject?

}

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete ){

 }


text:
Q: Which kind of DBs calculate rate per minute statistics? I have a use case requirement, where I want to design a hashtag ranking system. 10 most popular hashtag should be selected. My idea is something like this:
[hashtag, rateofhitsperminute, rateofhisper5minutes]
Then I will query, find out the 10 most popular #hashtags, whose rateofhits per minute are highest.
My question is what sort of databases, can I use, to provide me statistics like 'rateofhitsperminute' ?
What is a good way to calculate such a detail and store in it db ? Do some DBs offer these features?

A: First of all, "rate of hits per minute" is calculated:
[hits during period]/[length of period]

So the rate will vary depending on how long the period is. (The last minute? The last 10 minutes? Since the hits started being recorded? Since the hashtag was first used?)
So what you really want to store is the count of hits, not the rate. It is better to either:

*

*Store the hashtags and their hit counts during a certain period (less memory/cpu required but less flexible)

*OR the timestamp and hashtag of each hit (more memory/cpu required but more flexible)

Now it is a matter of selecting the time period of interest, and querying the database to find the top 10 hashtags with the most hits during that period.
If you need to display the rate, use the formula above, but notice it does not change the order of the top hashtags because the period is the same for every hashtag.

You can apply the algorithm above to almost any DB. You can even do it without using a database (just use a programming language's builtin hashmap).
If performance is a concern and there will be many different hashtags, I suggest using an OLAP database. OLAP databases are specially designed for top-k queries (over a certain time period) like this.
Having said that, here is an example of how to accomplish your use case in Solr: Solr as an Analytics Platform. Solr is not an OLAP database, but this example uses Solr like an OLAP DB and seems to be the easiest to implement and adapt to your use case:
Your Solr schema would look like:
<fields>
 <field name="hashtag"  type="string"/>
 <field name="hit_date" type="date"/>
</fields>

An example document would be:
{
 "hashtag": "java",
 "hit_date": '2012-12-04T10:30:45Z'
}

A query you could use would be:
http://localhost:8983/solr/select?q=*:*&facet=true&facet.field=hashtag&facet.mincount=1&facet.limit=10&facet.range=hit_date&facet.range.end=2013-01-01T00:00:00Z&facet.range.start=2012-01-01T00:00:00

Finally, here are some advanced resources related to this question:

*

*Similar question: Implementing twitter and facebook like hashtags

*What is the best way to compute trending topics or tags? An interesting idea I got from these answers is to use the derivative of the hit counts over time to calculate the "instantaneous" hit rate.

*HyperLogLog can be used to estimate the hit counts if an approximate calculation is acceptable.

*Look into Sliding-Window Top-K if you want to get really academic on this topic.

A: No database has rate per minute statistics just built in, but any modern database could be used to create a database in which you could quite easily calculate rate per minute or any other calculated values you need.
Your question is like asking which kind of car can drive from New York to LA - well no car can drive itself or refuel itself along the way (I should be careful with this analogy because I guess cars are almost doing this now!), but you could drive any car you like from New York to LA, some will be more comfortable, some more fuel efficient and some faster than others, but you're going to have to do the driving and refueling.

A: You can use InfluxDB. It's well suited for your use case, since it was created to handle time series data (for example "hits per minute").
In your case, every time there is a hit, you could send a record containing the name of the hashtag and a timestamp.
The data is queryable, and there are already tools that can help you process or visualize it (like Grafana).

A: If you are happy with a large data set you could store and calculate this information yourself.
I believe Mongo is fairly fast when it comes to index based queries so you could structure something like this.
Every time a tag is "hit" or accessed you could store this information as a row
[Tag][Timestamp]

Storing it in such a fashion allows you to first of all run simple Group, Count and Sort operations which will lead you to your first desired ability of calculating the 10 most popular tags.
With the information in this format you can then perform further queries based on tag and timestamp to Count the amount of hits for a specific tag between the times X and Y which would give you your hits Per period.
Benefits of doing it this way:

*

*High information granularity depending on time frames supplied via query

*These queries are rather fast in mongoDB or similar databases even on large data sets

Negatives of doing it this way:

*

*You have to store many rows of data

*You have to perform queries to retrieve the information you need rather than returning a single data row


text:
Q: onEach changes the dispatcher in StateFlow (kotlin coroutines) Imagine the following self-contained test case
@Test
fun `stateFlow in GlobalScope`() = runBlockingTest {

    suspend fun makeHeavyRequest(): String {
        return "heavy result"
    }

    val flow1 = flowOf(Unit)
        .map { makeHeavyRequest() }
        .onEach { logThread("1: before flowOn") }
        .flowOn(testDispatcher)
        .stateIn(GlobalScope, SharingStarted.Lazily, "init state")

    val flow2 = flowOf(Unit)
        .map { makeHeavyRequest() }
        .onEach { logThread("2: before flowOn") }
        .flowOn(testDispatcher)
        .stateIn(GlobalScope, SharingStarted.Lazily, "init state")
        .onEach { logThread("2: after stateIn") }

    val flow3 = flowOf(Unit)
        .map { makeHeavyRequest() }
        .onEach { logThread("3: before flowOn") }
        .flowOn(testDispatcher)
        .onEach { logThread("3: after flowOn") }
        .stateIn(GlobalScope, SharingStarted.Lazily, "init state")

    flow1.test {
        assertEquals("heavy result", expectItem())
        cancelAndIgnoreRemainingEvents()
    }

    flow2.test {
        assertEquals("heavy result", expectItem())
        cancelAndIgnoreRemainingEvents()
    }

    flow3.test {
        assertEquals("heavy result", expectItem())
        cancelAndIgnoreRemainingEvents()
    }

}

The effect of running it will be:
Thread (1: before flowOn): Thread[main @coroutine#2,5,main]
Thread (2: before flowOn): Thread[main @coroutine#3,5,main]
Thread (2: after stateIn): Thread[main @coroutine#6,5,main]
Thread (3: before flowOn): Thread[DefaultDispatcher-worker-1 @coroutine#8,5,main]
Thread (3: after flowOn): Thread[DefaultDispatcher-worker-1 @coroutine#4,5,main]

org.opentest4j.AssertionFailedError:
Expected :heavy result
Actual   :init state

In flow3 placing the onEach between flowOn and stateIn completely changes the dispatcher and messes up the result. Why is that?

A: You should use MainScope instead of GlobalScope.
Global Scope is an uncontrolled scope.
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html
You can find more good patterns in coroutines:
https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad

A: The reason this happens is because the stateIn operator has some optimizations depending on whether the upstream flow is a ChannelFlow.
.flowOn(...) returns a ChannelFlow while .onEach(...) does not.
Usually this would not really matter. Why it does matter in your case, is because you expect the flow returned by stateIn to never emit the initial value. But there is a reason this parameter is mandatory and you should expect to receive the initial value. Whether you actually do mostly depends on whether the upstream flow is able to emit a value without suspending.
Now it appears that the one of the optimizations in the stateIn operator is, that it might consume a ChannelFlow without suspending. Thats why you get your expected behavior when using
.flowOn(testDispatcher) /*returns ChannelFlow*/
.stateIn(GlobalScope, SharingStarted.Lazily, "init state")


text:
Q: typescript redux toolkit payloadaction lengthy error import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit"
import axios, { AxiosError} from "axios"

type user = {
    id: number,
    token: string
}

export type error = {
    error: string
}

interface authState {
    user: user | {},
    isFetching: boolean
    error?: error

}

export const authLogin = createAsyncThunk(
    'auth/login',
    async (credentials : { username: string, password: string}, { rejectWithValue}) => {
        try {
            const response = await axios.post("http://localhost:3001/auth/login", credentials)
            return response.data

        } catch (err : any) {
            const error : error = err.response.data || {error: "Server error"}
            return rejectWithValue(error)
        }
    }
)

const initialState: authState = {
    user: {},
    isFetching: true
}

export const authSlice = createSlice({
    name: "authReducer",
    initialState,
    reducers: {
        setUser: (state, action : PayloadAction<user>) => {
            state.user = action.payload
        }
    },
    extraReducers: (builder) => {

        // LOGIN
        builder.addCase(authLogin.pending, (state : authState) => {
            state.isFetching = true
        })
        builder.addCase(authLogin.fulfilled, (state: authState, action: PayloadAction<user>) => {
            const { id, token } = action.payload
            localStorage.setItem("messenger-token", token)
            state.user = action.payload
            state.user = {
                id: id,
                token: token
            }

        })
        /* errors here */
        builder.addCase(authLogin.rejected, (state : authState, action: PayloadAction<error>) => {
            state.error = action.payload
        })
    },
})

export const { setUser } = authSlice.actions

export default authSlice.reducer

error on the rejected
(alias) type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
    payload: P;
    type: T;
} & ([M] extends [never] ? {} : {
    meta: M;
}) & ([E] extends [never] ? {} : {
    error: E;
})

No overload matches this call.
  Overload 1 of 2, '(actionCreator: AsyncThunkRejectedActionCreator<{ username: string; password: string; }, {}>, reducer: CaseReducer<authState, PayloadAction<unknown, string, { arg: { ...; }; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ ...; } | ({ ...; } & {})), SerializedError>>):

I been on this error for a while.
I'm unsure how to fix this error. I'm returning an error type yet action: PayloadAction<error> gives this error.
I even console.log'd and made it error and it would output in the form of the error type. How to fix? Also, in the authLogin thunk I put err: any im unsure whether that is causing the error or not but what do i name the err without it erroring?

A: You just need to specify reject value type for inferring by typescript;
Add type to createAsyncThunk:
export const authLogin = createAsyncThunk<
  user, // Returned type
  { username: string; password: string }, // Params
  {
    rejectValue: error // Error type
  }
>("auth/login",

And you can now remove type hinting:
builder.addCase(authLogin.rejected, (state, action) => {
  state.error = action.payload
})

A: You can fill type for Error in PayloadAction like this:
builder.addCase(authLogin.rejected, (state, action: PayloadAction<PageType, string, void, Error>) => {
  state.error = action.payload
})


text:
Q: How can chips inside a disabled v-select be made clickable? I have a v-select that is representing the selected items with v-chips internally. I want the chips to be used as buttons when the user is not editing the selection, however the v-select is disabled when the user is not editing the selection. Since the v-select is disabled, none of the @click events I bind to the v-chip work, since the disable behavior cascades down to the v-chips. Since the v-select needs to be disabled to prevent the dropdown behavior, how can I enable my @click events on the v-chip elements.
See this CodePen for my rough setup: https://codepen.io/anon/pen/orLxMz

A: It looks like the disable property of the v-select adds a
pointer-events: none;

style to all of its descendants. This is what is preventing the @click events from firing.
To re-enable the v-chips for clicking, add the style
pointer-events: all;

to the v-chip declaration.
See this working CodePen: https://codepen.io/anon/pen/QXEKLN


text:
Q: Cloud Service ReservedIP mapping error when adding a load balancer I have below enpoints defined
<Sites>
  <Site name="Internal" physicalDirectory="location">
    <Bindings>
      <Binding name="HttpIn100" endpointName="HttpInLB" />
      <Binding name="HttpIn101" endpointName="HttpInLB" hostHeader="someheader" />
      <Binding name="HttpIn102" endpointName="HttpInLB" hostHeader="someheader" />
      <Binding name="HttpIn103" endpointName="HttpInLB" hostHeader="someheader" />
    </Bindings>
  </Site>
</Sites>

And this is the endpoint
<Endpoints>
      <InputEndpoint name="HttpInLB" protocol="http" port="80" loadBalancer="LB" />
    </Endpoints>

Then in my cscfg file I have
 <NetworkConfiguration>
<VirtualNetworkSite name="Development" />
<AddressAssignments>
  <InstanceAddress roleName="SiteName">
    <Subnets>
      <Subnet name="DMZ-subnet" />
    </Subnets>
  </InstanceAddress>
  <ReservedIPs>
    <ReservedIP name="ipname"/>
  </ReservedIPs>
</AddressAssignments>
<LoadBalancers>
  <LoadBalancer name="LB">
    <FrontendIPConfiguration type="private" subnet="DMZ-subnet" staticVirtualNetworkIPAddress="00.0.00.001" />
  </LoadBalancer>
</LoadBalancers>

When I publish, I get below error
ReservedIP 'ipname' was not mapped to an endpoint. The service definition must contain atleast one endpoint that maps to the ReservedIP.
Appreciate if someone could help me with this.
Many Thanks

A: ReservedIP is only supported with services containing an external endpoint. What you can do is add an external endpoint and block it with Network Security Groups.
For example, add following endpoint to your Endpoints tag. Then you could block the port using NSG.
<InputEndpoint name="Endpoint1" protocol="http" port="8078" />


text:
Q: mount encrypted sparseimage as home directory before login There are several ways (loginhook, launchdaemon etc.) to automount a sparsebundle before logging in, but there's none without writing down the password in plaintext for automount an encrypted sparsebundle.
Reading out the password from the keychain requires to unlock it before, therefore it's not possible to automate the process without user action.
#!/usr/bin/env bash -e
# SOURCE: http://risponderetag.wpdev8.com/p/35966.html

SPARSEBUNDLE_PATH="/Users/Shared/username.sparsebundle"
SPARSEBUNDLE_MOUNT_PATH="/Users/username/"
KEYCHAIN_PATH="/Users/username/Library/Keychains/login.keychain"

# Check existing states
if [ -e "$SPARSEBUNDLE_MOUNT_PATH" ]; then
    echo "Already mounted."
    exit 0
fi

# The mount command uses security find-generic-password
# to get the password from the keychain store
MOUNT_PASSWORD=$(security find-generic-password -w -D "disk image password" -l username.sparsebundle $KEYCHAIN_PATH)
printf $MOUNT_PASSWORD | hdiutil attach -stdinpass -mountpoint "$SPARSEBUNDLE_MOUNT_PATH" "$SPARSEBUNDLE_PATH"

For further informations see:
Can I mount an encrypted image BEFORE Finder loads?
http://techanic.net/2012/10/14/programmatically_mounting_encrypted_disk_images_in_os_x.html
Question (EDIT):
Are there other ways to pass a keychain password without using plaintext or user interaction?

A: So depending on the actual use case you are working with I may have an answer for your dilemma. If the location you are mounting to exists prior to actually mounting your disk, logging in before mounting the disk will create a default user filesystem with its very own login keychain. You can log in to a different account, mount the disk and save the password to the keychain, copy the password to the system keychain, and (after unmounting the disk) transfer the password to the unmounted user account login keychain. That item will exist prior to mounting so the disk can be automatically mounted on login. So you should be able to use that password with launch agents. Go into the password options and allow all applications to use it so you are not prompted for anything after it is in its final location.
If you cannot get launch agents to work, you can always write a short applescript app to refresh your finder to have the proper desktop to display and put it in the login items of the unmounted account so that it executes after the drive is mounted
delay 5
do shell script "killall Finder"

Put that into the /Users/Shared folder or something so it can be accessed before mounting and the mounting process does not interfere.
So that "kind of" does not require user interaction at least beyond the process of logging on. I hope that helps!


text:
Q: Best way to port a mobile website to a mobile app I have a website with a mobile interface (jQuery Mobile). I need to port it to a mobile app.
to make the website, I used Ruby on Rails.
I searched a lot and found many ways to port it such as PhoneGap, which seems to most viable solution.
However, I don't understand few things.
The most important part of my app will be the database. The iPhone/Android app will need to sync with the online website's database. So it need to store a local version and update every time the phone is connected to the internet.
How can I use PhoneGap with Rails? Can PhoneGap read Rails?

A: According to PhoneGap's FAQ:
"A PhoneGap application may only use HTML, CSS, and JavaScript. However, you can make use of network protocols (XmlHTTPRequest, Web Sockets, etc) to easily communicate with backend services written in any language. "
So using web requests you can communicate with your rails application, which then does the database work and returns any results you need, making it an API. I would look into these videos for setting up a rails web service to communicate with your mobile app.

A:
PhoneGap is an open source framework for quickly building
  cross-platform mobile apps using HTML5, Javascript and CSS.

So, you can not package Ruby code with PhoneGap.
The way you can use PhoneGap with Rails, is writing a "Rails API". So your mobile app (PhoneGap) make requests to your API to get/set data from database.
My suggestion is to use an MV* Javascript framework like backbone.js, with jQuery Mobile and PhoneGap to send/receive JSON messages to/from API.


text:
Q: How to make part of a text bold I have the following function in vba:
Function ConcatinateAllCellValuesInRange(sourceRange As Excel.Range) As String
        Dim finalValue As String

        Dim cell As Excel.Range

        i = 0
        For Each cell In sourceRange.Cells
        i = i + 1
        Rzad = cell.Row
            finalValue = finalValue & CStr(i) & ". " & CStr(Sheets(1).Cells(Rząd, 6)) & "/" & CStr(Sheets(1).Cells(Rząd, 7)) & ": " & Format(cell.Value, Bold) & "; " & vbCrLf

        Next cell

        ConcatinateAllCellValuesInRange = finalValue
    End Function

I want to make a part of the text bold but 'Format(cell.Value, Bold)' does not work. Can you suggest a solution?

A: try:
cell.Font.Bold = True

if you want the whole cell to be bold.
If you want to make only part of the cell content bold, see:
excel vba: make part of string bold


text:
Q: Permission Error When Exporting to $JAVA_HOME on MacOS Big Sur Whenever I try to set my Java Home export JAVA_HOME=$(/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home) in my .zshenv or .zshrc files, I get an /Users/{USER NAME HERE}/.zshenv:1: permission denied: /Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home error when starting up my terminal. In fact, I can't seem to be able to export anything (for example, export TEST=$(/Users/{USER NAME HERE}) gives me a zsh: permission denied: /Users/{USER NAME HERE} error. I already gave full disk access in system preferences, but that doesn't seem to be working either. I am the only user on my computer.

A: The $(foo) bit means, loosely, "run foo as a program, then insert its output here and go on as if I had typed it", which is not what you want here. Just do
export JAVA_HOME=/Library/Java/...

The $() bit is useful when you use the Mac's Java selection mechanism, and run e.g.
export JAVA_HOME=$(/usr/libexec/java_home -v16)

In that case, you're running a program, and setting JAVA_HOME to the output of that program.

A: Ran into the same issue today, and figured out out to fix it.
Remember to close/open your shell (or resource it) after making the change in your profile script.
In Z shell, the export statement is a bit different than bash, as you can set the environment variable without the $().
Instead of:
export JAVA_HOME=$(/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home)
Use the simpler zsh form with quote marks for the path:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home"