text:
Q: DC.js - adding loading GIF when dc.js charts are being filtered I'm trying to add a loading gif when a user clicks on a dc.js chart, a loading gif will appears stating that the dashboard is loading or filtering. When finish filtering, the loading gif will disappear. I have multiple charts in the dashboard. I think it would be tedious to state the .on('filtered', function(chart,filter){...}) to each chart. Is there a way or an API that will start an event whenever any charts are being filtered?
It tried using this but it doesn't support the .on(...) function

dc.on('filtered', function(...){...});

UPDATE!
I'm not sure if I'm doing this correctly. Like i saw above, I'm trying to add a feature when a user click on a row chart (dc.js), a loading gif will appear and will disappear after the charts finish redrawing or filter. I apply the code by over riding the onclick so the DIV (loading gif) will appear on the onclick then filter the charts.
        chart.on("renderlet", function(chart) {

        chart.selectAll('rect')
        .on('click', function(d) {
            $('#please-wait').css("display","block");
            console.log("click!", d);

            var filter = chart.keyAccessor()(d);

                dc.events.trigger(function () {
                    chart.filter(filter);
                    chart.redrawGroup();
                    $('#please-wait').css("display","none");
                });

        });

    });

Though, it sort of works. As in, if i remove the display: none line code, the please-wait will appear. If I apply the display:none line code, nothing happens because (I'm assume) the page quickly trigger the filter event before the please-wait div is actually appear in the front page. Is there a way to start the dc.events.trigger.. AFTER the please-wait Div actually appear in the front page? Am i doing this correctly or is there a better way?


text:
Q: Which method is to be applied and when? Consider the following problem:

*

*In how many ways 10 different balls can be put in 2 different boxes?

I solved this question like this:

*

*Consider two boxes($B_1$ and $B_2$). $B_1$ can be filled in 10 ways while $B_2$ can be filled in 9 ways. So, total number of cases is $10×9 = 90$. But solution was something different.

For each ball there are two options either to go in $B_1$ or $B_2$. So, total number of ways = $2×2×2...10$times = $2^{10}$

My Method does not fail in all problems.
When should I chose which method and why?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wrong row count using Catalog Queries I got this query on the following page:
http://docs.aws.amazon.com/redshift/latest/dg/c_join_PG_examples.html
It lists the table names along with row count. But the row count seems to be wrong (10 times than actual)
select datname, nspname, relname, sum(rows) as rows
from pg_class, pg_namespace, pg_database, stv_tbl_perm
where pg_namespace.oid = relnamespace
and pg_class.oid = stv_tbl_perm.id
and pg_database.oid = stv_tbl_perm.db_id
and datname ='tickit'
group by datname, nspname, relname
order by datname, nspname, relname;

Is the sum(rows) correct?

A: Here, try mine. It includes the data size as well. :-D
/*
   Ordered view of table sizes.
*/
CREATE VIEW my_schema.vw_table_summary
AS
SELECT db_name
      ,schema_name
      ,table_name
      ,TO_CHAR(rows_total,'999,999,999,999')  rows_total
      ,TO_CHAR(rows_sorted,'999,999,999,999') rows_sorted
      ,CASE WHEN rows_total > 0
            THEN ROUND((CONVERT(NUMERIC,rows_sorted)/CONVERT(NUMERIC,rows_total))*100,2)
       ELSE 0.00 END percent_sorted
      ,COALESCE(size_in_gb,0) size_in_gb
FROM (SELECT id        table_id
            ,datname   db_name
            ,nspname   schema_name
            ,relname   table_name
            ,SUM(rows) rows_total
            ,SUM(sorted_rows) rows_sorted
        FROM stv_tbl_perm
        JOIN pg_class
          ON pg_class.oid = stv_tbl_perm.id
        JOIN pg_namespace
          ON pg_namespace.oid = relnamespace
        JOIN pg_database
          ON pg_database.oid = stv_tbl_perm.db_id
       WHERE name NOT LIKE 'pg_%'
         AND name NOT LIKE 'stl_%'
         AND name NOT LIKE 'stp_%'
         AND name NOT LIKE 'padb_%'
         AND nspname <> 'pg_catalog'
       GROUP BY id, datname, nspname, relname
       ORDER BY id, datname, nspname, relname) tbl_det
LEFT
JOIN (SELECT tbl table_id
            ,ROUND(CONVERT(REAL,COUNT(*))/1024,2) size_in_gb
        FROM stv_blocklist bloc
       GROUP BY tbl) tbl_size
 ON tbl_size.table_id = tbl_det.table_id
 ORDER BY db_name
         ,schema_name
         ,table_name
;


text:
Q: Rails downcase params for an inclusion validation? So I have a validation for an invite code in a Rails 4 App with Devise. To create an account with devise the user has to enter a validation code. It looks like this:
class User < ActiveRecord::Base
  validates :invite_code, inclusion: {
    in: %w(foo347 bar362 foobarr100),
    message: "Rails 4 app is invite only at this time, please sign up for a code."
  }

It works great but I want to make it case insensitive so fOo347 or BaR362 will work . I tried doing a before_save  like so:
  before_save { |user| user.name = user.name.downcase }

per the instructions here
Simple way to always make a field lowercase in db  .
It's not working though, I think because it's a validation. I also tried swapping the before_save for a before_create with no luck. How can I downcase the field before it hits the validation?

A: You should use the before_validation callback instead:
before_validation { self.user.name = self.user.name.downcase }

A: How about you downcase the params at the controller?
or you can use before validation callback like taglia proposed


text:
Q: Multiple Images in NSMutableArray I am saving images from the camera in an NSMutableArray. When I add one picture, the picture is added to the array. But, the problem is that when I take another picture, the first picture is replaced by the second one. I want to save all of the pictures taken by the camera.
- (IBAction)takePhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

    [self presentViewController:picker animated:YES completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *cameraImage = info[UIImagePickerControllerEditedImage];
    self.tempView.image = cameraImage;
    camImages = [NSMutableArray arrayWithCapacity:10];
    [camImages addObject:self.tempView.image];
    //self.chosenImages=camImages;
    NSLog(@"the image is=%@",camImages);
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

A: Take away  camImages = [NSMutableArray arrayWithCapacity:10]; and put it in viewDidLoad.
EDIT: Use this instead:
UIImage *cameraImage = info[UIImagePickerControllerEditedImage];
self.tempView.image = cameraImage;

if(!camImages)camImages = [[NSMutableArray alloc]init];

camImages = [NSMutableArray arrayWithCapacity:10];
[camImages addObject:self.tempView.image];
//self.chosenImages=camImages;
NSLog(@"the image is=%@",camImages);
[picker dismissViewControllerAnimated:YES completion:NULL];

A: The problem it's because [NSMutableArray arrayWithCapacity:10]; actually allocates a new position in memory for a array, and your pointer camImages are pointing for a new array, losing the reference for the old one you allocated previously.
So, whenever you take a new photo, a new memory position for the array will be allocated, with just the current image.
To resolve this problem, you should allocate this array only once, and use the same memory position for the array to add your images.
As Abdullah Shafique pointed, you can allocate this array once in the some previous method, like viewDidLoad, or just use lazy instantiation, with a if in your delegate method.
if(!camImages){
     camImages = [NSMutableArray new];
}


text:
Q: moviepy VideoFileClip IndexError: list index out of range, OSError: MoviePy error: failed to read the duration of file We are recording videos from the browser with the following encoding
'video/webm; codecs="vp8, opus"', then we upload these videos to an AWS S3 bucket.
Our ML model works on these videos, and one of the models needs to extarct the audio and process it.
Here is a code snapit for extracting the audio
import speech_recognition as sr
import moviepy.editor as me
from denoise2 import denoise
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import math

model_name = 'bert-base-nli-mean-tokens'
model = SentenceTransformer(model_name)

class recomm:
    y = 0.0

    def __init__(self, path, keywords):
        video_clip = me.VideoFileClip(r"{}".format(path))
        path2 = "y2.wav"
        video_clip.audio.write_audiofile(r"{}".format(path2), nbytes=2)
        recognizer = sr.Recognizer()
        """a = AudioSegment.from_wav(path2)
        a = a + 5
        a.export(path2, "wav")"""
        audio_clip = sr.AudioFile("{}".format(path2))
        with audio_clip as source:
            audio_file = recognizer.record(source)
        sent = []
        result = ""
        try:
            result = recognizer.recognize_google(audio_file)
        except sr.UnknownValueError:
            print("Can not process audio ")
        if not result:
            self.y = 0
        else:
            print(result)
            sent.append(result)
            sent = sent + keywords
            sent_vec3 = model.encode(sent)
            x = cosine_similarity(
                [sent_vec3[0]],
                sent_vec3[1:]
            )
            for i in range(len(x)):
                self.y = self.y + x[0][i]
            self.y = (self.y / (len(sent) - 1)) * 1000.0

    def res(self):
        if self.y < 0:
            self.y = 0
        return self.y

And that's the traceback,
the error occurred at this line
video_clip = me.VideoFileClip(r"{}".format(path))

Traceback (most recent call last):
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/moviepy/video/io/ffmpeg_reader.py", line 286, in ffmpeg_parse_infos
match = re.findall("([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", line)[0]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 90, in
main()
File "main.py", line 85, in main
interviews_channel.start_consuming()
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/pika/adapters/blocking_connection.py", line 1865, in start_consuming
self._process_data_events(time_limit=None)
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/pika/adapters/blocking_connection.py", line 2026, in _process_data_events
self.connection.process_data_events(time_limit=time_limit)
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/pika/adapters/blocking_connection.py", line 833, in process_data_events
self._dispatch_channel_events()
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/pika/adapters/blocking_connection.py", line 567, in _dispatch_channel_events
impl_channel._get_cookie()._dispatch_events()
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/pika/adapters/blocking_connection.py", line 1492, in _dispatch_events
consumer_info.on_message_callback(self, evt.method,
File "main.py", line 79, in callback
processing(json.loads(body))
File "main.py", line 34, in processing
r = recomm(path, keywords)
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/recommendation.py", line 17, in init
video_clip = me.VideoFileClip(r"{}".format(path))
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/moviepy/video/io/VideoFileClip.py", line 88, in init
self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt,
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/moviepy/video/io/ffmpeg_reader.py", line 35, in init
infos = ffmpeg_parse_infos(filename, print_infos, check_duration,
File "/home/medo/Dev/Smart-remotely-interviewing-system/backend/Process-interview/test/lib/python3.8/site-packages/moviepy/video/io/ffmpeg_reader.py", line 289, in ffmpeg_parse_infos
raise IOError(("MoviePy error: failed to read the duration of file %s.\n"
OSError: MoviePy error: failed to read the duration of file 74b74292-3642-486a-8319-255bb7e7da5a-1647363285285.webm.
Here are the file infos returned by ffmpeg:

ffmpeg version 4.2.2-static https://johnvansickle.com/ffmpeg/ Copyright (c) 2000-2019 the FFmpeg developers
built with gcc 8 (Debian 8.3.0-6)
configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gmp --enable-libgme --enable-gray --enable-libaom --enable-libfribidi --enable-libass --enable-libvmaf --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libdav1d --enable-libxvid --enable-libzvbi --enable-libzimg
libavutil 56. 31.100 / 56. 31.100
libavcodec 58. 54.100 / 58. 54.100
libavformat 58. 29.100 / 58. 29.100
libavdevice 58. 8.100 / 58. 8.100
libavfilter 7. 57.100 / 7. 57.100
libswscale 5. 5.100 / 5. 5.100
libswresample 3. 5.100 / 3. 5.100
libpostproc 55. 5.100 / 55. 5.100
Input #0, matroska,webm, from '74b74292-3642-486a-8319-255bb7e7da5a-1647363285285.webm':
Metadata:
encoder : Chrome
Duration: N/A, start: 0.000000, bitrate: N/A
Stream #0:0(eng): Audio: opus, 48000 Hz, mono, fltp (default)
Stream #0:1(eng): Video: vp8, yuv420p(progressive), 640x480, SAR 1:1 DAR 4:3, 29.42 fps, 29.42 tbr, 1k tbn, 1k tbc (default)
Metadata:
alpha_mode : 1
At least one output file must be specified


text:
Q: Unable to restrict backslash to single slash in the username in connection string C# Below is the code that I am using for connection string. The user name is ZA\Ankur.Deshpande. But I am getting error if I am putting 1 backslash and if I use @ it still gives me 2 backslash and its failing during my connection open.
var s = @"ZA\Ankur.Deshpande";
string connectionString =
"Data Source=03RNBL-5CD717;" +
                      "database = ankur; uid = " + s + " password = uuwwss@1988; ";
con.Open();

A: Add two back slashes instead of a single back slash, without using @.


text:
Q: only submit server side request when date in date range is in valid format I am using YADCF with date range filter.  I am using the jQuery-ui datepicker type.  Data is returned to the datatable from AJAX requests (serverSide is set in the datatables config).
This works fine as long as the user selects a valid date from the UI box.  However, the user can also enter free text into the box (e.g '20') and when this happens the server side raises an exception and returns error 400.  This is ok but the ideal solution would be for the date format to be validated client-side, and the AJAX request is only sent when there is a valid date in the range box.
Is it possible to configure yadcf / datatables to only submit AJAX requests when there is a valid date?
yadcf.init(table, [
  {
    column_number: 0,
    filter_type: 'range_date',
    datepicker_type: 'jquery-ui',
    date_format: 'yyyy-mm-dd',
    filter_delay: 500,
    filter_container_id: 'timestamp_range_picker'
  }
]

A: You should probably fix this issue at the source, which is your input box.  Set it as a date type and then there will be no chance of incorrect entry.
<input type="date" />


text:
Q: Laravel 5 - Custom User Authentification with LDAP I would like to create a custom user authentification with LDAP - this is how it should work:
User enters his credentials - I'll check with LDAP is the user exists, if yes I'll create a session in a database and return a valid token for a request. The token handler is not the problem, but I'm not sure about the LDAP Authentification.
What I've already done:
activated php_ldap extension

Installed the php-ldap-module for L5 with the description from here:
http://packalyst.com/packages/package/strebl/l5-ldap-auth
So now I've got my new Authentification Provider, but when I'll try with:
if (Auth::attempt(['email' => 'user', 'password' => 'password']))
{
    .....
}

Nothing happens - no error, no warning. Can I use now Auth::attempt, or is that another function for checking if a user exists in my LDAP Directory. Is it still email and password as properties for the login attempt?
Is there somebody who is working with this extension and can give me some more information about the usage?
Thanks in advance

A: You can try to follow these instructions:
laravel-simple-ldap-auth
There it is explained how to create a custom LDAP authentication in Laravel 5.


text:
Q: How can I get a value from LiveData? I am using Room for the first time. I am having a look at the LiveData concept. I know that we can fetch records from DB into LiveData and haveObservers attached.
@Query("SELECT * FROM users")

<LiveData<List<TCUser>> getAll();

But I am performing sync in the background, where I need to fetch data from server and compare it with the data in RoomDatabase table called "users" and then either insert,update or delete from users table. How can I traverse the LiveData list before taking any action ? As it gives error if I put it in for loop.
OR should I not use LiveData for this scenario ?
I guess I need to call
<LiveData<List<TCUser>> getAll().getValue()

But is it the right thing to do ? Here is some more code to give idea as to what I am trying to do:
List<User>serverUsers: Is the data received from a response from an API

private void updateUsers(List<User> serverUsers) {
    List<UserWithShifts> users = appDatabase.userDao().getAllUsers();
    HashMap<String, User> ids = new HashMap();
    HashMap<String, User> newIds = new HashMap();

    if (users != null) {
        for (UserWithShifts localUser : users) {
            ids.put(localUser.user.getId(), localUser.user);
        }
    }

    for (User serverUser : serverUsers) {
        newIds.put(serverUser.getId(), serverUser);

        if (!ids.containsKey(serverUser.getId())) {
            saveShiftForUser(serverUser);
        } else {
            User existingUser = ids.get(serverUser.getId());
            //If server data is newer than local
            if (DateTimeUtils.isLaterThan(serverUser.getUpdatedAt(), existingUser.getUpdatedAt())) {
                deleteEventsAndShifts(serverUser.getId());
                saveShiftForUser(serverUser);
            }
        }
    }

Where:
@Query("SELECT * FROM users")
List<UserWithShifts> getAllUsers();

Is the first line in updateUsers() the right way to fetch data from DB to process before inserting new ones or should it be instead
<LiveData<List<User>> getAll().getValue()

Thanks,

A: If I understand your architecture correctly, updateUsers is inside of an AsyncTask or similar.
This is my proposed approach, which involves tweaking your Dao for maximum effectiveness. You wrote a lot of code to make decisions you could ask your database to make.
This is also not tight or efficient code, but I hope it illustrates more effective use of these libraries.
Background thread (IntentService, AsyncTask, etc.):
/*
 * assuming this method is executing on a background thread
 */
private void updateUsers(/* from API call */List<User> serverUsers) {
    for(User serverUser : serverUsers){
        switch(appDatabase.userDao().userExistsSynchronous(serverUser.getId())){
            case 0: //doesn't exist
                saveShiftForUser(serverUser);
            case 1: //does exist
                UserWithShifts localUser = appDatabase.userDao().getOldUserSynchronous(serverUser.getId(), serverUser.getUpdatedAt());
                if(localUser != null){ //there is a record that's too old
                    deleteEventsAndShifts(serverUser.getId());
                    saveShiftForUser(serverUser);
                }
            default: //something happened, log an error
        }
    }
}

If running on the UI thread (Activity, Fragment, Service):
/*
 * If you receive the IllegalStateException, try this code
 *
 * NOTE: This code is not well architected. I would recommend refactoring if you need to do this to make things more elegant.
 *
 * Also, RxJava is better suited to this use case than LiveData, but this may be easier for you to get started with
 */
private void updateUsers(/* from API call */List<User> serverUsers) {
    for(User serverUser : serverUsers){
        final LiveData<Integer> userExistsLiveData = appDatabase.userDao().userExists(serverUser.getId());
        userExistsLiveData.observe(/*activity or fragment*/ context, exists -> {
            userExistsLiveData.removeObservers(context); //call this so that this same code block isn't executed again. Remember, observers are fired when the result of the query changes.
            switch(exists){
                case 0: //doesn't exist
                    saveShiftForUser(serverUser);
                case 1: //does exist
                    final LiveData<UserWithShifts> localUserLiveData = appDatabase.userDao().getOldUser(serverUser.getId(), serverUser.getUpdatedAt());
                    localUserLiveData.observe(/*activity or fragment*/ context, localUser -> { //this observer won't be called unless the local data is out of date
                        localUserLiveData.removeObservers(context); //call this so that this same code block isn't executed again. Remember, observers are fired when the result of the query changes.
                        deleteEventsAndShifts(serverUser.getId());
                        saveShiftForUser(serverUser);
                    });
                default: //something happened, log an error
            }
        });
    }
}

You'll want to modify the Dao for whatever approach you decide to use
@Dao
public interface UserDao{
    /*
     * LiveData should be chosen for most use cases as running on the main thread will result in the error described on the other method
     */
    @Query("SELECT * FROM users")
    LiveData<List<UserWithShifts>> getAllUsers();

    /*
     * If you attempt to call this method on the main thread, you will receive the following error:
     *
     * Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.
     *  at android.arch.persistence.room.RoomDatabase.assertNotMainThread(AppDatabase.java:XXX)
     *  at android.arch.persistence.room.RoomDatabase.query(AppDatabase.java:XXX)
     *
     */
    @Query("SELECT * FROM users")
    List<UserWithShifts> getAllUsersSynchronous();

    @Query("SELECT EXISTS (SELECT * FROM users WHERE id = :id)")
    LiveData<Integer> userExists(String id);

    @Query("SELECT EXISTS (SELECT * FROM users WHERE id = :id)")
    Integer userExistsSynchronous(String id);

    @Query("SELECT * FROM users WHERE id = :id AND updatedAt < :updatedAt LIMIT 1")
    LiveData<UserWithShifts> getOldUser(String id, Long updatedAt);

    @Query("SELECT * FROM users WHERE id = :id AND updatedAt < :updatedAt LIMIT 1")
    UserWithShifts getOldUserSynchronous(String id, Long updatedAt);
}

Does this solve your problem?
NOTE: I did not see your saveShiftForUser or deleteEventsAndShifts methods. Insert, Save and Update are performed synchronously by Room. If you are running either method on the main thread (I'm guessing this is where your error is coming from), you should create a daoWrapper that is returned from appDatabase like so:
public class UserDaoWrapper {
    private final UserDao userDao;

    public UserDaoWrapper(UserDao userDao) {
        this.userDao = userDao;
    }

    public LiveData<Long[]> insertAsync(UserWithShifts... users){
        final MutableLiveData<Long[]> keys = new MutableLiveData<>();
        HandlerThread ht = new HandlerThread("");
        ht.start();
        Handler h = new Handler(ht.getLooper());
        h.post(() -> keys.postValue(userDao.insert(users)));
        return keys;
    }

    public void updateAsync(UserWithShifts...users){
        HandlerThread ht = new HandlerThread("");
        ht.start();
        Handler h = new Handler(ht.getLooper());
        h.post(() -> {
            userDao.update(users);
        });
    }

    public void deleteAsync(User... users){
        HandlerThread ht = new HandlerThread("");
        ht.start();
        Handler h = new Handler(ht.getLooper());
        h.post(() -> {
            for(User e : users)
                userDao.delete(e.getId());
        });
    }
}


text:
Q: How to override HTMLTags LabelFor Using HTMLTags and JimmyMVC conventions I have in a view the following:
@Html.FormBlock(aModel => aModel.PostQuery.ProjectId)

But the label is generated as "PostQueryProjectId"
How can I override the generator to just return "ProjectId"?

A: Add annotation in PostQuery model
class PostQuery
{
[Display(Name="Post Query")]
public int ProjectId {get; set; }
...
}

A: Steven,
I think you can override the conventions by implementing your own HtmlConventionRegistry
public class DefaultAspNetMvcHtmlConventions : HtmlConventionRegistry
{
    public DefaultAspNetMvcHtmlConventions()
    {
        Labels.Always.ModifyWith(er => er.CurrentTag.Text(er.Accessor.Name));
    }
}

Then apply your registry before adding it to your IoC container (here is mine for structuremap)
public class HtmlTagRegistry : Registry
{
    public HtmlTagRegistry()
    {
        var htmlConventionLibrary = new HtmlConventionLibrary();
        new DefaultHtmlConventions().Apply(htmlConventionLibrary);
        new DefaultAspNetMvcHtmlConventions().Apply(htmlConventionLibrary);
        For<HtmlConventionLibrary>().Use(htmlConventionLibrary);
    }
}


text:
Q: Angular Typescript send optional restful url params only if they are not empty Current system that I have control of is only the front end which is Angular 5 ( thus Typescript)  .  Backend should not matter, but there is a team in which they are not changing their signatures, their error handling etc..  :/
Issue is that there is a search screen in which only 1 field is required, so when I am trying to send a URL to a Restful backend ( actually as I type this.. this is not really restful, is it? )
My Angular Service method:
getSearchByUserResults(first,last,user,eff,term,emp) {

       //IF I JUST DO THIS, THEN EMPTY PARAMS ARE SENT AND SOMEHOW THE BACKEND IS NOT SET UP TO HANDLE THAT  :/
       //var params = "userid=" + user + "&first-name=" + first + "&last-name=" + last + "&eff-date=" + eff + "&term-date=" + term + "&employee-id=" + emp;

    //Sending only userid works
    //var params = "userid=" + user;

    // Send user and first when first name is empty(null) again it does NOT work
    var params = "userid=" + user + "&first-name=" + first;

    var searchUser = this._searchByUser + params;

    return this._http.get(searchUser).map((response: Response) => response.json()).catch(this.handleError);
}

Basically what I am showing is in the comments above.

If a param is empty or null, then I DO NOT want it to be added to the list of params send to the server controller method...

*

*if user = 123  send  http://server.com:9080//rest/config/users?userid=123

*if user and first name not empty send  http://server.com:9080//rest/config/users?userid=123&first-name=Ted

*Never send something with empty params like this empty first-name   http://server.com:9080//rest/config/users?userid=123&first-name=
Based on that list of params, how can I do this without a bunch of if statements checking for null/empty/undefined  ?
first,last,user,eff,term,emp

A: It turns out, I had misread the docs, and HttpParams will not automatically remove null values.
You can, however, make use of an array function for this:
getParams(first,last,user,eff,term,emp): HttpParams {
    let obj = {first, last, user, eff, term, emp};
    return Object.keys(obj).reduce((params, key) =>
            obj[key] ? params.append(key, obj[key]) : params, new HttpParams())
}

This will build up an HttpParams object that only includes truthy values, so it will exclude null / undefined / empty strings etc.
Bear in mind that false and 0 are also falsey values-- I'm not sure if this will be an issue in your use case.


text:
Q: open source Graph class for c++ I'm going to write a framework for implementation of algorithms on graphs. Of course I have to write my own Graph class, but at first I want to see what good implementations of this kind of class are there exist. I only know about boost::graph. What other open source C++ libraies could you suggest to look at?

A: Stick with boost:graph. It's a mature and high quality library, so I see no reasons why you should look further than that.
And using it + studying its source will help you more than if you fumble about trying to make your own graph class without taking a look at proven libraries.


text:
Q: How to import a large size (5.5Gb) CSV file to Postgresql using ruby on rails? I have huge CSV file of 5.5 GB size, it has more than 100 columns in it. I want to import only specific columns from the CSV file. What are the possible ways to do this?
I want to import it to two different tables. Only one field to one table and rest of the fields into another table.
Should i use COPY command in Postgresql or CSV class or SmartCSV kind of gems for this purpose?
Regards,
Suresh.

A: If I had 5Gb of CSV, I'd better import it without Rails! But, you may have a use case that needs Rails...
Since you've said RAILS, I suppose you are talking about a web request and ActiveRecord...
If you don't care about waiting (and hanging one instance of your server process) you can do this:
Before, notice 2 things: 1) use of temp table, in case of errors you don't mess with your dest table - this is optional, of course. 2) use o option to truncate dest table first
CONTROLLER ACTION:
def updateDB
    remote_file = params[:remote_file]   ##<ActionDispatch::Http::UploadedFile>
    truncate = (params[:truncate]=='true') ? true : false
    if remote_file
        result = Model.csv2tempTable(remote_file.original_filename, remote_file.tempfile) if remote_file
        if result[:result]
            Model.updateFromTempTable(truncate)
            flash[:notice] = 'sucess.'
        else
            flash[:error] = 'Errors: ' + result[:errors].join(" ==>")
        end
    else
        flash[:error] = 'Error: no file given.'
    end
    redirect_to somewhere_else_path
end

MODEL METHODS:
# References:
# http://www.kadrmasconcepts.com/blog/2013/12/15/copy-millions-of-rows-to-postgresql-with-rails/
# http://stackoverflow.com/questions/14526489/using-copy-from-in-a-rails-app-on-heroku-with-the-postgresql-backend
# http://www.postgresql.org/docs/9.1/static/sql-copy.html
#
def self.csv2tempTable(uploaded_name, uploaded_file)
    erros = []
    begin
        #read csv file
        file = uploaded_file
        Rails.logger.info "Creating temp table...\n From: #{uploaded_name}\n "
        #init connection
        conn = ActiveRecord::Base.connection
        rc = conn.raw_connection
        # remove columns created_at/updated_at
        rc.exec "drop   table IF EXISTS #{TEMP_TABLE}; "
        rc.exec "create table #{TEMP_TABLE} (like #{self.table_name}); "
        rc.exec "alter table #{TEMP_TABLE} drop column created_at, drop column updated_at;"
        #copy it!
        rc.exec("COPY #{TEMP_TABLE} FROM STDIN  WITH CSV HEADER")

        while !file.eof?
          # Add row to copy data
          l = file.readline
          if l.encoding.name != 'UTF-8'
              Rails.logger.info "line encoding is #{l.encoding.name}..."
              # ENCODING:
              # If the source string is already encoded in UTF-8, then just calling .encode('UTF-8') is a no-op,
              # and no checks are run. However, converting it to UTF-16 first forces all the checks for invalid byte
              # sequences to be run, and replacements are done as needed.
              # Reference: http://stackoverflow.com/questions/2982677/ruby-1-9-invalid-byte-sequence-in-utf-8?rq=1
              l = l.encode('UTF-16', 'UTF-8').encode('UTF-8', 'UTF-16')
          end
          Rails.logger.info "writing line with encoding #{l.encoding.name} => #{l[0..80]}"
          rc.put_copy_data(  l  )
        end
        # We are done adding copy data
        rc.put_copy_end
        # Display any error messages
        while res = rc.get_result
          e_message = res.error_message
          if e_message.present?
            erros << "Erro executando SQL: \n" + e_message
          end
        end
    rescue StandardError => e
        erros << "Error in csv2tempTable: \n #{e} => #{e.to_yaml}"
    end
    if erros.present?
        Rails.logger.error erros.join("*******************************\n")
        { result: false, erros: erros }
    else
        { result: true, erros: [] }
    end

end

# copy from TEMP_TABLE into self.table_name
# If <truncate> = true, truncates self.table_name first
# If <truncate> = false, update lines from TEMP_TABLE into self.table_name
#
def self.updateFromTempTable(truncate)
    erros = []
    begin
        Rails.logger.info "Refreshing table #{self.table_name}...\n Truncate: #{truncate}\n "
        #init connection
        conn = ActiveRecord::Base.connection
        rc = conn.raw_connection
        #
        if truncate
            rc.exec "TRUNCATE TABLE #{self.table_name}"
            return false unless check_exec(rc)
            rc.exec "INSERT INTO #{self.table_name} SELECT *, '#{DateTime.now}' as created_at, '#{DateTime.now}' as updated_at FROM #{TEMP_TABLE}"
            return false unless check_exec(rc)
        else
            #remove lines from self.table_name that are present in temp
            rc.exec "DELETE FROM #{self.table_name} WHERE id IN  ( SELECT id FROM #{FARMACIAS_TEMP_TABLE} )"
            return false unless check_exec(rc)
            #copy lines from temp into self  + includes timestamps
            rc.exec "INSERT INTO #{self.table_name} SELECT *, '#{DateTime.now}' as created_at, '#{DateTime.now}' as updated_at FROM #{FARMACIAS_TEMP_TABLE};"
            return false unless check_exec(rc)
        end

    rescue StandardError => e
        Rails.logger.error  "Error in updateFromTempTable: \n #{e} => #{e.to_yaml}"
        return false
    end

    true
end


text:
Q: How do I apply a different background image to the  tag? I need to apply different background images to the home page < html > tag and the inside pages of a site. In order to do this the references need to be unique.
Without using class or id, how do I differentiate between the tags?
I tried this, but it doesn't validate:
<html class="inside"...

Thanks!

A: Add the class to your body element, where it is valid.
Then do
body.inside {
    background-image: url(/path/to/it.png) repeat;
}

A: If you're talking about different background images for different pages, I guess you'll need to create a different stylesheet for each different background you want, and just make sure to include the appropriate stylesheet from each page.

A: Inline stylesheet for each different page:
<style> html { background-image: url(someimage.png); } </style>

A: You want this:
CSS:
#home { background: ... ; }
body { background: ... ; }

HTML:
<body id="home">

</body>

Other pages:
<body>

</body>

A: You should consider using IDs. That way you can keep all the references to your background images in your CSS file. E.g.
#background-main  { background-image:url(background-main.jpg) }
#background-page1 { background-image:url(background-page1.jpg) }
#background-page2 { background-image:url(background-page2.jpg) }

You would then just have to reference the ID of the background image you want to have displayed. E.g.
<body id="background-main">

Alternatively, you could use classes.
This approach will make it easier for you to maintain your site.


text:
Q: unix_timestamp for 2019-03-31T15:29:42.443-07:00 I am running hive query to convert string to timestamp format:
References from:

*

*https://help.sumologic.com/03Send-Data/Sources/04Reference-Information-for-Sources/Timestamps%2C-Time-Zones%2C-Time-Ranges%2C-and-Date-Formats

*how can I check a string of datetime in hive whether meet requirement?
Query:
select `timestamp`, unix_timestamp(`timestamp`,"yyyy-MM-dd'T'hh:mm:ss'X'")
from tbl1
where eventdate="2019-03-31"
limit 2;

Result:
2019-03-31T15:29:42.443-07:00   NULL
2019-03-31T13:35:10.929-07:00   NULL

I tried:
unix_timestamp(`timestamp`,"yyyy-MM-dd'T'hh:mm:ssX")
unix_timestamp(`timestamp`,"yyyy-MM-dd'T'hh:mm:ss:SSSX")
unix_timestamp(`timestamp`,"yyyy-MM-dd'T'hh:mm:ss:SSSZZZZ")
unix_timestamp(`timestamp`,"yyyy-MM-dd'T'hh:mm:ss:SSSZZ:ZZ")

I am getting NULL but not the timestamp converted.
Thanks.

A: Correct format is
"yyyy-MM-dd'T'HH:mm:ss.SSSX"

*

*you have 24HRS, not 12 am/pm, it corresponds to HH, not hh. See SimpleDateFormat for reference

A: unix_timestamp(timestamp,"yyyy-MM-dd'T'hh:mm:ss.SSSX") works


text:
Q: Multidimensional array access by class with multiple variables Ok, so this is a shot in the dark but...
Is there any way to overload the argument for multidimensional array access to take in custom arguments?
//normal array access
myArray[1][2];

//I have a class with two ints and do this
myArray[int2Var.x][int2Var.y];

//is there any way to overload the array arguments so I can do this to access a two dimensional array?
myArray[int2Var];

I am currently working in Java but I would also like to know if it is at all possible.

A: No. Java does not support operator overloading in the way C++ does.
Here's a Java version, in case you're interested:
public class Test {

    public static class Index
    {
        int x;
        int y;
    }
    public static <T> T get(T[][] array, Index i)
    {
        return array[i.x][i.y];
    }
    public static void main(String[] args)
    {
        Index ix = new Index();
        ix.x = 1;
        ix.y = 2;

        Integer[][] arr = new Integer[3][3];
        for (int i=0; i<3; i++)
            for (int j=0; j<3; j++)
                arr[i][j] = 3*i + j;

        System.out.println(get(arr,ix));
    }
}

Method get(...) takes an array of any reference type and an index object and returns the selected object.  For primitives you'd need one specialized get method per primitive type.
Note also that array syntax in java is not [a,b] but [a][b].


text:
Q: Writing a long (primitive type) to a file in Java Hi all,
I have an array of long that I would like to write into a .txt file that I can later open in gedit (one number per line). I get those values by using a subtraction of two instances of System.currentTimeMillis().
I use the following code:
BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
for (int i = 0; i < USER_LIMIT; ++i) {
    out.write(latency[i] + "\n");
}
out.close();

When looking at the file, I do see:
0
1
1
0

I believe the string concatenation converted the long into an integer. If I use the DataOutputStream, then I cannot read it back with gedit or any notepad/text editor, it just looks like garbage (I believe it's writing bytes).
Would anyone please let me know how I can fix my problem please?
Thank you very much!

A: There is nothing wrong with your code. What you think is in latency ... isn't.
public static void main(String[] args) throws IOException
{
    long[] latency = { 123456789000L, 234567890000L, 345678901000L };

    BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
    for (int i = 0; i < 3; ++i) {
        out.write(latency[i] + "\n");
    }
    out.close();
}

produces:
$ more latency.txt
123456789000
234567890000
345678901000

When you're having a problem with code like this, it's often beneficial to write a small test case to narrow down the problem.

A: Cast to a Long and use toString:
out.write(((Long)latency[i]).toString() + "\n");

Or just use the static toString:
out.write(Long.toString(latency[i]) + "\n");

A: When you use DataOutputStream to write a long it is using a different encoding of your data than gedit understands.
One of the most common encodings used for text files is ASCII. With this each byte represents a character in a table. This table has 128 characters. When you write a string to a file using Java the way you're doing it this is what is happening and gedit understands that encoding. If you convert a long to a string the maximum size a long can be would look like: 9223372036854775807. That would take up 19 bytes.
A long in Java is 64 bits or 8 bytes. When you use DataOutputStream a long gets written to the file as 8 bytes. A text editor like gedit does not understand this encoding.
What further complicates things is encodings such as UTF-8.

A: You don't need to append the newline to the number, so you can break them apart and avoid this problem. Try this:
for ( int i = 0; i < USER_LIMIT; ++i ) {
    out.write( String.valueOf(latency[i]) ); // Or Long.toString(long)
    out.write( '\n' ); // Or simply out.newLine()
}


text:
Q: How to order and re-order video clips added to iDVD? I don't think I can find a valid answer for this: how do I actually order or re-order the video clips I added to iDVD?
I actually have video clips named
01 some title
02 some other title
03 the third title
04 ...

total 11 of them, and I selected all 11 files in Finder, and then dragged them into iDVD.  So the DVD Map showed the correct order of those clips, and Project -> About also showed the assets in the correct order.
However, after the DVD is made, when I was watching program 01, and pressed Next on the DVD set top box remote, then I would see the very beginning of program 04...  Is it out of order?  If so, can it be fixed or changed at all?


text:
Q: How to play videostreaming from internet android? I have this streaming
http://www.tvrey.com/canal_5.html

I have tried with two ways
but always I got
Can't play this video.
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoViewActivity extends Activity {

    // Declare variables
    ProgressDialog pDialog;
    VideoView videoview;

    // Insert your Video URL
    String VideoURL = "http://www.androidbegin.com/tutorial/AndroidCommercial.3gp";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the layout from video_main.xml
        setContentView(R.layout.videoview_main);
        // Find your VideoView in your video_main.xml layout
        videoview = (VideoView) findViewById(R.id.VideoView);
        // Execute StreamVideo AsyncTask

        // Create a progressbar
        pDialog = new ProgressDialog(VideoViewActivity.this);
        // Set progressbar title
        pDialog.setTitle("Android Video Streaming Tutorial");
        // Set progressbar message
        pDialog.setMessage("Buffering...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        // Show progressbar
        pDialog.show();

        try {
            // Start the MediaController
            MediaController mediacontroller = new MediaController(
                    VideoViewActivity.this);
            mediacontroller.setAnchorView(videoview);
            // Get the URL from String VideoURL
            Uri video = Uri.parse(VideoURL);
            videoview.setMediaController(mediacontroller);
            videoview.setVideoURI(video);

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        videoview.requestFocus();
        videoview.setOnPreparedListener(new OnPreparedListener() {
            // Close the progress bar and play the video
            public void onPrepared(MediaPlayer mp) {
                pDialog.dismiss();
                videoview.start();
            }
        });

    }

}

and this is the other way copied from this link
http://code.tutsplus.com/tutorials/streaming-video-in-android-apps--cms-19888

but I get same result.

A: Try to register the setOnErrorListener(MediaPlayer.OnErrorListener l) to check if there is any error occurs during preparation or playback.


text:
Q: Getting error with conda install using custom channel to install from local tar file I'm trying to install PyAlgoTrade using a tar.gz file I downloaded from their GitHub page (it's not on Binstar).  I edited my .condarc file to include "- file://~/conda_repo".  Then I try to install, with the following results:
$ conda install PyAlgoTrade-0.16
Fetching package metadata: .Error: Could not find URL:
file://~/conda_repo/osx-64/
$ ls ~/conda_repo/osx-64/
PyAlgoTrade-0.16.tar.gz
The ls results clearly show that the URL is correct.  I'm thinking that there is an extra environment / config setup that I'm missing and not finding in the conda documentation.  Any help in resolving this mystery would be appreciated.  Thanks.

A: You are making a few mistakes here. The first, and most important one, is that the file you downloaded is not a conda package.  So conda won't be able to install it.  It looks like it is a Python package, so you can install it with pip: pip install PyAlgoTrade-0.16.tar.gz.

To clarify some other mistakes you made:
File urls cannot contain ~. Use the full path to your home directory.  Also note that if this were a conda package, you would need to run conda index on that directory to do make a local repo like this. And (again, if it were), an easier way would be to conda install downloaded-conda-package.tar.bz2 (that is, run conda install on the downloaded file directly).


text:
Q: How to loop inside array and assign to a variable In my angular2 application which contains checkboxes; the checkbox keys are stored in an array named "ticketselected" and the selected check boxes keys are stored in "selectedArray". I want to assign these keys one by one to a variable and use that variable. I need to splice an array. How can I implement this?
what I have done is:
component.ts
this.ticketSelected
    .map((entry, key) => {
         if (entry == true) {
             selectedArray.push(key);
            }
     })

 var index =   // This should be key
 allTickets.splice(index, 1);

'selectedArray' contains all selected keys.
How should I implement this?
EDIT
 deleteRequest
      .subscribe((data: any) => { // this data contain deleted data ie like {count:1}
                this.ticketSelected
                     .map((entry, key) => {
                      if (entry === true) {
                                selectedArray.push(key);
                       }
                 })

                 selectedArray.forEach((item) => {
                        var index = allTickets.indexOf(item);
                        console.log("index", index);
                        if (index != -1){
                            allTickets.splice(index, 1);
                    }
                    });
                })

A: You should use indexOf method.
allTickets=allTickets.filter(function(item){
     return selectedArray.indexOf(item.id)==-1;
});

Atnoher solution is to use filter method which accepts a callback function, applied to every item in the array.
Read more here.


text:
Q: How to get Not Installed Plugins in QGIS? I am new to QGIS.
I am trying to export the Voronoi polygon Coordinates to CSV.
I have searched in net for that mmqgis plugin has to be installed but after installing the software in manage and plugin tools, not installed option is not showing.
How do I install that plugin and is there any other way to export?

A: Open the plug-in manage and install dialog from the menu (Plugins/Manage and Install plugins...).

*

*Select not installed plugins

*start typing the name of the plugin in Search field (mm)

*Select the mmqgis plugin from the list

*Click on the install plugin button


text:
Q: Combining These Two Scripts I'm trying to combine two scripts to run simultaneously but I can't get both of them to run. Below are the two separate scripts.
  function onEdit(event) {
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 7;
  var tableRange = "A2:T399"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
  var range = sheet.getRange(tableRange);
  range.sort( { column : columnToSortBy, ascending: false } );
  }
}

and
function onEdit(event)
{
  var timezone = "GMT-5";
  var timestamp_format = "MM-dd-yyyy"; // Timestamp Format.
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestamp";
  var sheet = event.source.getSheetByName('Area Check-in'); //Name of the sheet where you want to
run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated'
header exists, but not in the header row itself!
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
cell.setValue(date);
  }
}

I'm not sure if I need to name them individually. And if so, how would I add the names?

A: function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()=='NameOfSheetYouWantThisToWorkOn') {
    if(e.range.columnStart==7) {
      e.range.getSheet().getRange("A2:T399").sort({column:7,ascending:false});
    }
  }
  if(sh.getName()=='Area Check-in') {
    var headers=sh.getRange(1,1,1,sh.getLastColumn()).getValues()[0];
    var dateCol=headers.indexOf("Timestamp")+1;
    var updateCol=headers.indexOf("Parent Sign-Out")+1;
    if (dateCol>0 && e.range.rowStart>1 && e.range.columnStart == updateCol) {
      sh.getRange(e.range.rowStart,dateCol).setValue(Utilities.formatDate(new Date(), "GMT-5", "MM-dd-yyyy"));
    }
  }
}


text:
Q: Trying to match nodes between similar graphs I am looking for an algorithm to match nodes in similar graphs. The number of nodes are not equal, but each graph does represent the same system.
So, I'm looking for similar or fuzzy graph matching or pattern recognition.
Where do I start?
Undirected
Vertex-labelled
Multigraph
Weighted
Sparse
Nodes: 2,172
Edges: 3,000
Nodes have a number of independent attributes. Edges have one attribute, similar to length. Node and edge attributes are not identical for corresponding nodes and edges between the two graphs.
This problem is described in technical papers as partial isomorphism, graph alignment and maximum common subgraph

A: Here's a basic algorithm for partial isomorphism between two graphs A and B ..

Algorithm
Given:
- graph A
- graph B
- threshold on A, p in [0.0,1.0)
- threshold on B, q in [0.0,1.0)

1. define: list T = { Nodes in graph B }

2. define: c = 0

3. for every Node i in graph A
   {
       for every Node j in list T
       {
           if(i and j are equivlant)
           {
               c = c + 1

               remove j from list T
           }
       }
   }

4. calculate: x = number of nodes in graph A / c

5. calculate: y = number of nodes in graph B / c

6. return (x > p AND y > q)

Example
Rule: Node i and Node j are equivalent if they have same degree.
Constant: Threshold on A, p = 0.95 ~ 95%.
Constant: Threshold on B, q = 0.75 ~ 75%.
Output: The algorithm will return TRUE for any graph B that has set of nodes that make of 75% or more of it equivalent to set of nodes that make 95% or more of graph A


text:
Q: Is this an issue with my math, or did I do something wrong with the user input? I am making a simple BMI calculator to practice Java formatting and such and forth, but every time I run the code, I input weight and height and it returns me with "0.0"! I use eclipse and it says nothing is wrong with the code. Please help?
PS: Sorry for newb
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {

        //Variables
        System.out.println("Please enter your height in inches: ");
        int height = input.nextInt();
        System.out.println("Please enter your weight in pounds: ");
        int weight = input.nextInt();

 //BMI Calcs
 int newHeight = height*height;
 double initBMI = weight/newHeight;
 double BMI = 703*initBMI;
 System.out.println(BMI);
    }
}


text:
Q: Rolling motion in space Is rolling motion possible in space?
If so,
Let's imagine that two cylinders of different masses and inertias were rolled over an incline in space is it the case that the one with lower inertia will reach further as the later? Or they will also reach the same distance along each other as in earth?
The core of my question is mass always irrelevant to velocity in rolling motion or is it a "gravity" special case?

A: Rolling motion is not only possible in space, but it's even highly likely. If you throw an object in a space that's absent of any significant gravitational field, assuming of course the object is not a theoretical "point mass", it will in general always undergo two motions: a linear one due to the force applied on its center of mass, and a rotational one in which all its parts revolve around its own center of mass. The latter will only be absent in the special case where there was no torque at all applied in the initial throw. Anyone who threw a ball knows that's a bit tricky: even if you do your best to avoid giving the ball a spin, you will still see it slightly rotating due to the "inhomogeneity" of the initial force which leads to a net torque.
It's not very clear how you would roll an object on an inclined plane where there is no gravity. However, if your question is basically about whether the moment of inertia still affects the rotational speed, the answer is undoubtedly yes. If you throw a rod in such a situation and it begins rotating, and now you imagine that you can order this rod to shorten by pressing a button on a remote, you will see the shortened rod rotating faster. So the angular speed is definitely dependent on its moment of inertia, which is a consequence of conservation of angular momentum. And since the moment of inertia depends both on the geometry of the object and on its mass, then no, the speed of rolling is not independent of mass, and the same is true under the influence of gravity.
I know that there is a slight confusion sometimes about the moment of inertia and rolling speed: there is a popular demonstration of two cylinders of equal mass but different mass distributions, and it is shown that due to their different moments of inertia there will still be one that reaches the bottom of an inclined plane before the other. This can lead to a misunderstanding that mass does not affect the moment of inertia. But mass does: both the mass and the mass distribution are factors in determining the moment of inertia. If we can model our object by $n$ mass particle each one of mass $m_i$ which is some distance $r_i$ away from the center of mass then the moment of inertia $I$ is given by:
$$I = \sum_{i=1}^n{m_{i}r_{i}^2} $$
And if our object now has some angular momentum $L$ then the relation with its angular speed $\omega$ is:
$$ \omega = \frac{L}{I} $$
Which in particular explains why when we shortened our rod, angular speed had to increase: $\omega$ must increase to compensate for the decrease in $I$ (which occurs due to a decrease in our $r_i$'s), in order to conserve $L$.

A: I assume by space you really mean microgravity.
For something to roll you need friction, and friction is generated by contact forces that are perpendicular to the contacting surfaces.
So a device might push on these cylinders against the ramp and achieve rolling, just like a cam-roller situation.
But if left on their own there is nothing to motive these rollers to move at all, and hence nothing to make them roll on surface.


text:
Q: Inverter diagonal principal multiplicando diagonal secundária Estou desenvolvendo esse algoritmo, preciso inverter a diagonal principal e em seguida, multiplicar somente a diagonal secundária por 2, exemplo:
Ele está assim:
[9, 1, 2, 4]
[5, 6, 7, 8]
[3, 2, 1, 0]
[1, 2, 3, 4]

Preciso deixar ele assim:
[4, 1, 2, 8]
[5, 1, 14, 8]
[3, 4, 6, 0]
[2, 2, 3, 9]

Isso é o que tenho até agora:
dimensao = int(input())

matriz = []
for linha in range(dimensao):
    linha = [int(coluna) for coluna in input().split()]
    matriz.append(linha)

transposta = []
for linha in range(dimensao):
    transposta.append([])
    for coluna in range(dimensao):
        ent = matriz[coluna][linha]
        transposta[linha].append(ent)

for linha in transposta:
    for coluna in linha:
        print(coluna, end= ' ')
    print(end="\n")

A: Possivelmente existe uma maneira mais esperta pra fazer isso, mas de qualquer forma segue uma ideia:
matriz = [[9, 1, 2, 4],
          [5, 6, 7, 8],
          [3, 2, 1, 0],
          [1, 2, 3, 4]]

j = 0
tamanho_matriz = len(matriz)
lista = []

# Adicionando os elementos da diagonal principal a uma lista
for i in range(tamanho_matriz):
    lista.append(matriz[i][j])
    j = i + 1

# invertendo a lista da diagonal principal e adicionando os valores de volta na matriz
j = 0
invertida = lista[::-1] # aqui acontece a inversão da lista
for i in range(tamanho_matriz):
    matriz[i][j] = invertida[i]
    j = i + 1

# multiplicando a diagonal secundaria
j = tamanho_matriz - 1
for i in range(0, tamanho_matriz):
    matriz[i][j] = matriz[i][j] * 2
    j -= 1

# imprimindo a matriz
for i in range(tamanho_matriz):
    for j in range(tamanho_matriz):
        print(f'{matriz[i][j]:2} ', end=' ')
    print()

A: Não precisa complicar (aliás, nem sei porque você criou a matriz transposta, não tem nada a ver com o problema).
Bom, no seu código você usou a mesma variável dimensao para percorrer as linhas e colunas, então estou assumindo que sempre será uma matriz quadrada.
Como estamos interessados apenas nas diagonais, dá para simplificar os loops. Basta pensar que a diagonal principal são os elementos em que a linha é igual à coluna (ou seja, os elementos nas posições (0, 0), (1, 1), etc). Então só precisa de um loop para percorrer essas posições.
Depois, para inverter, basta trocar a primeira posição com a última (no caso, seria trocar a (0, 0) com a (3, 3)), depois trocar a segunda com a penúltima, e assim por diante. Desta forma, eu só preciso iterar até a metade da diagonal, que no final ela estará invertida.
Já para a diagonal secundária, o cálculo é diferente: na primeira linha, o elemento da diagonal secundária está na última coluna. Na segunda linha, é o elemento da penúltima coluna e assim por diante. Novamente, basta um loop pelas linhas, pois a coluna pode ser calculada. E aí é só percorrer todas as linhas e multiplicar o valor por 2.
Ficaria assim:
# assumindo que as dimensões foram determinadas anteriormente e que a matriz já foi lida, etc
# assumindo também uma matriz quadrada
dimensao = 4
matriz = [
  [9, 1, 2, 4],
  [5, 6, 7, 8],
  [3, 2, 1, 0],
  [1, 2, 3, 4]
]

# diagonal principal, posições em que linha e coluna são iguais
# para inverter só precisa ir até a metade:
# troca o primeiro com o último, o segundo com o penúltimo, etc
for i in range(dimensao // 2): # "i" é a linha e a coluna
    dest = dimensao - i - 1 # posição que será trocada com esta
    matriz[i][i], matriz[dest][dest] = matriz[dest][dest], matriz[i][i]

# diagonal secundária
# primeira linha, última coluna; segunda linha, penúltima coluna, etc
for i in range(dimensao):
    matriz[i][dimensao - i - 1] *= 2 # multiplica por 2

print(*matriz, sep='\n')

Saída:
[4, 1, 2, 8]
[5, 1, 14, 8]
[3, 4, 6, 0]
[2, 2, 3, 9]

Também dá pra fazer tudo em um único loop. Só temos que garantir que a diagonal principal vá até a metade:
matriz = [
  [9, 1, 2, 4],
  [5, 6, 7, 8],
  [3, 2, 1, 0],
  [1, 2, 3, 4]
]

for i in range(dimensao):
    dest = dimensao - i - 1
    if i < dimensao // 2:
        matriz[i][i], matriz[dest][dest] = matriz[dest][dest], matriz[i][i]
    matriz[i][dest] *= 2

print(*matriz, sep='\n')


text:
Q: App won't work on iPhone 4 What settings do I have to change to allow my app to work on iPhone 4? Some people can install it on their iPhone 4's but have problems and others can't.
Is it related to the Required Device Capabilities entry?

A: Under the general tab for your project check what your deployment target is set to.  If you have it set to iOS 7 then iPhone users running iOS 4,5,6 will not be able to install your app.  Set this to the minimum iOS 7 version you want to support and then you will need to make sure your app works on all those iOS versions for it to run on all iPhone 4s.


text:
Q: Monitor broken or changed settings? Blues have lines and whites with yellow tint Very recently, my Lenovo y510p laptop's monitor has been having display problems with blues and whites. In my setup I also have a second monitor connected to the laptop. The second monitor has no display issues. My graphics cards include an Intel HD Graphics 4600 and an NVIDIA GT750M.
Using this photo as an example, this is what the screen currently looks like here. Changing contrast settings in the Intel Graphics sort of removes the yellowish tint to white areas in the screen but nothing is perfect.
Could the display have been damaged or could something have come loose? I travel with my laptop in a backpack at least 4 days of the week. Is this a hardware issue (display rather than graphics card)?
Adding something new, after some period of time later without changing, moving or doing anything to the laptop the display suddenly goes back to normal.


text:
Q: how to remove a particular row of data from influxdb I have some data in influxdb that is unnecessary, like some values like "0", so how do i delete those particular once. My database name is "bootstrap" and my measurement name is "response_time"
Tried this "delete from response_time where time > 2016-01-22T06:32:44Z"
but it says "Server returned error: error parsing query: found -01, expected SELECT, DELETE, SHOW, CREATE, DROP, GRANT, REVOKE, ALTER, SET at line 1, char 44"
Tried this also: "delete from bootstrap where time > 2016-01-22T06:32:44Z"

A: The current release of InfluxDB is a bit painful with deletes.  You can drop an entire measurement, or a particular series, or an entire database, or the part of a series older than 'x' (retention policy). Anything finer-grained than this is still a bit alpha. Apparently, it was more flexible in v 0.7, but that feature has gone away. Probably not the answer you were hoping for, sorry.
See here:
https://docs.influxdata.com/influxdb/v0.9/query_language/database_management/
(shameless self-promotion follows)
A similar set of questions were asked here.  Beware: it seems some answers depend on which version of InfluxDB you use.
My answer, which seems to be version-independent (so far):

Because InfluxDB is a bit painful about deletes, we use a schema that has a boolean field called "ForUse", which looks like this when posting via the line protocol (v0.9):
your_measurement,your_tag=foo ForUse=TRUE,value=123.5 1262304000000000000

You can overwrite the same measurement, tag key, and time with whatever field keys you send, so we do "deletes" by setting "ForUse" to false, and letting retention policy keep the database size under control.
Since the overwrite happens seamlessly, you can retroactively add the schema too. Noice.

Doing this, you can set up your Grafana queries to include "WHERE ForUse = TRUE". By filtering this way, and updating the "ForUse" field, you can replicate the functionality of "deleting" or "undeleting" points.
It's a bit kludgy, but I'm used to kludgy - every time series database I've worked with seems a bit awkward with partial deletes, so it must be something about their nature.


text:
Q: Auto numbering based on repeating cells I need help auto numbering a spreadsheet that has submissions with inventors but some submissions have multiple people listed, but need to be numbered the same.
e.g.:
No.     Count     Name
0011    1         Joe
0012    0.5       Sam
0012    0.5       Alex
0013    1         Ryan

The Count is determined by how many people the submission is divided up against. The Number represents the submission, so #0012 is Sam's and Alex's so they need to be numbered the same. I'm hoping there's an easy way I can number the worksheet rather than going and numbering each one individually. I need a formula that will auto-number the Count and Name records depending on if the Count repeats.

A: You'll need to set your first number manually with the formula below.
=TEXT(11,"0000")

In the next cell below, enter this formula and fill down the column:
=IF(AND(B3=B2,COUNTIF(A$2:A2,A2)<1/B3),TEXT(A2,"0000"),TEXT(A2+1,"0000"))

This works on the idea that the only time you don't want to augment the number is when the count is the same as the previous record and the number above isn't already listed the appropriate number of times. (The appropriate number of times is equal to 1/Count.) This second condition is necessary because of cases like rows 10 through 13 in the example, where groups of the same size follow each other in the table.

A: How do you know that Sam and Alex are associated with the same submission and not each co-submitters of different projects?  You need some basis for grouping.  The reliable way to do it would be to add a column that is unique to the submission, like the submission title, to serve as a unique identifier.  You sort the list on that.  Then increment the numbering if the unique ID is different from the previous row.
For example, assume col A is the unique ID, B is your No., C is the count, and D is Name, and what you are showing as the first row of data (0011) is row 2.  A general formula that you could copy for all cells in B (based on B2), would be:
=if(row()=2,1,if(a2=a1,b1,b1+1))

You can get fancy with formatting if you want to force leading zeros.
It is not good practice, but if you are manually ensuring that the list is sequential and this is all you have to work with, you could do something like this: Assume Col A is your No., B is Count, C is Name.  Add a new column D (which could be hidden).  Again row 2 is the first data row.  A general formula for all cells in D (based on D2), would be:
=if(b2=1,1,if(b1=1,b2,if(row()=2,b2,d1+b2)))

This identifies when each submission group ends in case you have several sequential multiple submissions.
The general formula for your No. (based on A2), would be:
=if(row()=2,1,if(d1=1,a1+1,a1))

Again, you can format to force leading zeros.
Edit: Recognize that relying only on the sequence in which you entered the data to do the numbering (my second example and Excellll's solution), is risky if there is any chance that the data sequence could change, for example, by accidentally sorting the data. The numbering logic would fall apart and give you incorrect results.  Incorporating a unique ID for each submission provides a foolproof way to recover (simply sort on the ID).


text:
Q: Binding IDataErrorInfo to window IsEnabled button property I have a WPF sub window with some input controls that the user has to correctly fill before pressing Ok button.
I have already implemented the interface IDataErrorInfo to validate all properties bound to UI Controls.
Now I would like that the IsEnabled property of Ok button is True only if ALL controls are valid, otherwise it has to be set to False.
It should be easy but I cannot find the correct solution. Do you have any suggestion?
Thanks in advance!

A: Ciao ;-)
I think you could bind the IsEnabled property of the button to (e.g.) the IDataErrorInfo.Error property of your data through a IValueConverter (that you have to implement) that converts from string to bool (e.g if the value if String.Empty than return true).
Another solution is to use Commands and have this logic enclosed in the CanExecute: in this way you just have to associate the Command with your Button.
HTH


text:
Q: How print python method documentation using inspect or __doc__ method I have following code :
import os
import imp
import sys
import inspect
import urlparse
from cgi import escape

def get_module(ClassName, Path):
    fp, pathname, description = imp.find_module(ClassName, [Path])
    module_loaded = imp.load_module(ClassName, fp, pathname, description)
    return module_loaded

def get_class_members(className):
    print "Members of  "+str(className)
    member_functions = inspect.getmembers(className,    predicate=inspect.ismethod)
    for each_item in member_functions:
        print each_item[0].__doc__

def get_all_classes(path, module):

    module_loaded = None
    sys.path.append(path)

    module_loaded = get_module(module, path)

    if None != module_loaded:
        class_list = module_loaded.get_all_classes()
        print "classes are "+str(class_list)
        return class_list

def main():
    class_list = get_all_classes('.', 'Class_Interface_File')
    for each_class in class_list:
        temp_module = get_module(each_class, '.')
        my_class = getattr(temp_module, each_class)
        instance = my_class()
        get_class_members(instance)
        print "-----------"

if __name__ == "__main__":
    main()

Class_Interface_file returns a list of classnames example ['Social', 'Audio']
I have issue here in method get_class_members. I want to print the comments for each member function I discover through inspect.getmembers. I dono how to concat className with value of each_item.
or is it possible to directly print documentation of member functions which comes from each_item ?
please help on this.

A: Okay, did some playing around with your code....
I have a class Triangle in a module triangle with some methods.
>>>import inspect
>>>import triangle
>>>mems = inspect.getmembers(triangle.Triangle)
>>>mems
[('__doc__', None), ('__init__','<unboound method.....>), etc)]

getmembers() returns a list of tuples.
So in your code, looping through this, you're asking for each_item[0].__doc__, [0] refers to the string containing the name of the function. So that line returns just the __doc__ of string objects. Changing this to [1] will return the __doc__ for the actual method:
>>>mems[3][0]  #the name of the function itself
'drawEquilateral'
>>>#here I reference the second tuple element of the fourth member
...
>>>mems[3][1].__doc__
'draw an equilateral triangle'
>>>"Method %s:  %s" %(mems[3][0], mems[3][1].__doc__)
'Method drawEquilateral: draw an equilateral triangle'

Hope this helps.


text:
Q: Demonstrate how to delete a particular key or keys from an S3 bucket using boto3 This boto3 function allows for deletion of a list of keys from an S3 bucket.  Please could you demonstrate an example of how to use it with:

*

*a single key to be deleted.

*a list of multiple keys to be deleted.

With thanks.
delete_objects(**kwargs)
This operation enables you to delete multiple objects from a bucket using a  single HTTP request. You may specify up to 1000 keys.

Request Syntax

response = bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'string',
                'VersionId': 'string'
            },
        ],
        'Quiet': True|False
    },
    MFA='string',
    RequestPayer='requester'
)

A: Delete one object:
response = bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'myObjectKey'
            }
        ]
    }
)

Delete two objects:
response = bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'myFirstObjectKey'
            },
            {
                'Key': 'mySecondObjectKey'
            }
        ]
    }
)

I feel like the documentation (which you linked) makes this extremely obvious. I'm curious as to how you found the documentation confusing.

A: Answer:
# Delete key(s)
forDeletion = [{'Key':'IMG_20160807_150118.jpg'}, {'Key':'IMG_20160807_150124.jpg'}]
response = bucket.delete_objects(Delete={'Objects': forDeletion})

for elem in response.get('Deleted'):
    print(elem['Key'])

Output:
IMG_20160807_150118.jpg
IMG_20160807_150124.jpg


text:
Q: When setting text on a TextView it takes way too long to display the text on screen I'm setting the text on a text view to a String that is 14,000,000  characters long.
This takes anywere from 1 to 5 minutes to load on screen(depending on device). Any Ideas how I can speed this up?
Here is the relevant code:
  responseView.text = requestResponsePair.second
 .....................
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context="com.salesrabbit.android.sales.universal.features.lumberjack.TextDisplayFragment">

 <TextView
     android:id="@+id/request_label"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/request_label_string"
     android:textSize="20sp"/>

 <TextView
     android:id="@+id/text_view_request"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

 <TextView
     android:id="@+id/response_label"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/response_label_string"
     android:textSize="20sp"/>

 <TextView
     android:id="@+id/text_view_response"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

  </LinearLayout>

A: Approach One
Recently, Google announced the PrecomputedText which is available for SDK level 28 and above. Along with that, the PrecomputedTextCompat has been released which is available for SDK 21 to 27. I haven't try it yet but there is a Medium article from Chris Craik called "Prefetch Text Layout in RecyclerView" which explains how to make use of it and how much workload gets off the UI thread without missing any frames.
Snippet from article
Precomputing
val precomputedText : Spannable = PrecomputedTextCompat.create(expensiveText, params)

Set precomputed text to TextView
TextViewCompat.setPrecomputedText(myTextView, precomputedText)

Make sure to read the docs, as some posting to a background thread is required.
Approach Two
Split your text into small chunks or paragraphs. Put it into a list and use a simple RecyclerView to show each item in the list. It's simple and you will get for free good performance as RecyclerView will render and process the items that are visible to the user.
Also, make sure to listen to the Episode 90: Spanspanspanspan of the Android Developers Backstage podcast, it is hosted by developers of the Android Engineering team.

A: Use PrecomputedText
Using PrecomputedText is one of the best approaches here. Read an answer by Giorgos Neokleous.
Turn off hyphenation
Turn off hyphenation also helps to improve performance significantly. You can do that by setting android:hyphenationFrequency="none" for a specific TextView or overriding that property for the whole application:
<!-- res/values/styles.xml -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- ... -->
    <item name="android:textViewStyle">@style/AppTextView</item>
</style>

<style name="AppTextView" parent="BaseAppTextView">
    <item name="android:hyphenationFrequency">none</item>
</style>

<style name="BaseAppTextView" parent="android:Widget.TextView"/>

<!-- res/values-21/styles.xml -->
<style name="BaseAppTextView" parent="android:Widget.Material.TextView"/>

Also take a look at few links:

*

*Use Android Text Like a Pro presentation by Siyamed Sinir from the Android Dev Summit '18 where he describes both approaches with some details.

*Prefetch Text Layout in RecyclerView article in Android Developers blog that can help make your RecyclerView faster.

A: That text is far too long. You should divide them by \n (divide into paragraphs) and put each paragraph into a textview in a recyclerview.
Tradeoff is that users cannot select all of the text or in-between paragraphs but i believe at the end it will be a better UX.
Then you should apply Precomputedtext.


text:
Q: Automatically-reconnecting TCP tunnel I have an unreliable network connection between two machines: sometimes active TCP connections get dropped for reasons beyond my control. I want to establish a reliable TCP connection between the two machines.
If the network was reliable, I'd just run ssh -L 1234:localhost:1234 remotehost, with the server listening on port 1234 on remotehost, and point the client at localhost:1234. But if the ssh connection dies, so will the forwarded connection. How can I arrange to automatically restore the connection between the client and the server?
Non-solutions:

*

*This isn't for interactive applications, so screen does not apply.

*This isn't just about reconnecting an SSH tunnel automatically, � la autossh. I want to continue using the same tunneled TCP connection, not start a new one.

*In principle, a VPN would do the trick. But it seems overkill when I just want one TCP connection, and I'd like a solution that works even if I don't have root permissions on either side.

I have a dim memory of a program called rocks that did just that, but it seems to have fallen off the face of the web. I'm mostly interested in Linux on both sides (though I'd expect a program at this level to be portable to other unices), but if you know of a program that works between QNX and VMS, all the better.

A: Is the old an unmaintained Reliable Sockets (Rocks) what you're looking for ?

A: The only standard protocol I know of with this capability is MPTCP. It is transparent to the application layer, so SSH on top of MPTCP should just work. It can run the underlying TCP connections over different paths with different IPs, so in principle it could be used to migrate your SSH connection in and out of the VPN connection depending on whether the VPN connection is up.
I don't know much about the maturity of MPTCP implementations, but the design of the protocol looks quite robust.
It should protect your SSH connections from getting lost due to flaky network connectivity. It won't protect you against a mitm who wants to break your SSH connection. A mitm can still inject corrupted data, which SSH will detect and break the connection.
An MPTCP like reconnect method build into the SSH protocol would be the method I could imagine keeping a connection alive for the longest possible time. But I don't think such a feature has been designed for the SSH protocol.

A: You could use daemontools to keep the ssh port forward up; it won't necessarily keep programs depending on the connection alive while it's down (as presumably when ssh disconnects the local port will start refusing their connections), but it's a start.
I suspect there are some iptables tricks, like causing that port to DROP packets as soon as the ssh forward goes away, so the connecting programs just know that packets are disappearing, not being refused.  I'm just learning daemontools myself (again) so I'm not sure if you can run a custom script when a service dies, but I suspect you can.

A: TCP does this automatically. You need only disable or weaken the typical practical cleanup hacks used to kill moribund TCP connections. Disable TCP keepalive for your connection, and greatly increase the limit for excessive retransmissions. On Linux, for example, write a large number into /proc/sys/net/ipv4/tcp_retries2.
However, in a modern network a stateful packet inspection firewall is likely to forget about a TCP connection which fails to exchange packets regularly, so it may rain on your parade.


text:
Q: Sandbox not working. Error: Sorry to interrupt: force:showPanel I have a Sandbox environment which is constantly failing to work no matter what page I try and access (including Setup pages) and giving this error message in a popup:

Sorry to interrupt
  force:showPanel

And this message in the console:

home:5 Refused to execute inline script because it violates the
  following Content Security Policy directive: "script-src 'self'
  'nonce-null' chrome-extension: 'unsafe-inline' 'unsafe-eval'
  https://sfdc.azureedge.net *.visualforce.com
  https://ssl.gstatic.com/accessibility/". Note that 'unsafe-inline' is
  ignored if either a hash or nonce value is present in the source list.

Before I got stuck with the above message, I got this message:

It does not matter which page I try and load (Home, Setup, Account etc), I will always get the Sorry to interrupt. force:showPanel error.

A: I believe this was caused by a bug in Salesforce and has now been fixed in our Sandbox.

A: We had the same problem this morning with our test sandbox.
The message was displayed after login with Lightning.
The problem was fixed (by Salesforce?) in the meantime and everything is working as expected.


text:
Q: using controller functions to display multiple pages Lets say i have multiple public functions in a single controller, i am trying to fine a way to display 1 option per page for example, first page user selects a schoolYear then hit submit, next page the user selects a school and hit submit, 3rd page the user selects a term and with a final page of all the selected fields being shown and a delete button. i am starting to test my page now and am wondering what is the best way to accomplish this?
class SchoolYearsController extends AppController
{
public function index()
{

}

public function chooseYear()
{
    $schoolYearsTable = $this->loadModel('SchoolYears');

    $schoolYears = $schoolYearsTable->find()->order(['SchoolYears.endYear'=>'desc']);

    $this->set('schoolYears',$schoolYears);

    $this->request->getSession()->write('App.schoolYear',$this->request->getData('schoolYear'));

    return $this->redirect(['controller'=>'SchoolYears', 'action'=>'chooseSchool']);
}

public function chooseSchool()
{
    $schoolListsTable = $this->loadModel('Schools');

    $schoolYear = $this->session->read('App.schoolYear');
    $schools = $schoolListsTable->find()
    ->where([
        'fiscalYear' => $schoolYear,
        'districtCode' => 'MA',
    ])
    ;

    $this->set('schools',$schools);

    return $this->redirect(['controller'=>'SchoolYears', 'action'=>'chooseTerm']);
}

public function chooseTerm()
{
    $chosenTerm = $this->request->getData();
}
}


text:
Q: What exactly are strings in Nim? From what I understand, strings in Nim are basically a mutable sequence of bytes and that they are copied on assignment.
Given that, I assumed that sizeof would tell me (like len) the number of bytes, but instead it always gives 8 on my 64-bit machine, so it seems to be holding a pointer.
Given that, I have the following questions...

*

*What was the motivation behind copy on assignment? Is it because they're mutable?

*Is there ever a time when it isn't copied when assigned? (I assume non-var function parameters don't copy. Anything else?)

*Are they optimized such that they only actually get copied if/when they're mutated?

*Is there any significant difference between a string and a sequence, or can the answers to the above questions be equally applied to all sequences?

*Anything else in general worth noting?
Thank you!

A: The definition of strings actually is in system.nim, just under another name:
type
  TGenericSeq {.compilerproc, pure, inheritable.} = object
    len, reserved: int
  PGenericSeq {.exportc.} = ptr TGenericSeq
  UncheckedCharArray {.unchecked.} = array[0..ArrayDummySize, char]
  # len and space without counting the terminating zero:
  NimStringDesc {.compilerproc, final.} = object of TGenericSeq
    data: UncheckedCharArray
  NimString = ptr NimStringDesc

So a string is a raw pointer to an object with a len, reserved and data field. The procs for strings are defined in sysstr.nim.
The semantics of string assignments have been chosen to be the same as for all value types (not ref or ptr) in Nim by default, so you can assume that assignments create a copy. When a copy is unneccessary, the compiler can leave it out, but I'm not sure how much that is happening so far. Passing strings into a proc doesn't copy them. There is no optimization that prevents string copies until they are mutated. Sequences behave in the same way.
You can change the default assignment behaviour of strings and seqs by marking them as shallow, then no copy is done on assignment:
var s = "foo"
shallow s


text:
Q: Terminal: segmentation fault 11 while reading file and counting the amount of vowels The terminal keeps saying: segmentation fault 11.
My code is:
int main()
{
    FILE *file;
    file=fopen("test.txt","r");
    int c;
    int vowelCount=0;

    while ((c=getc(file)!=EOF)) {

        if( c=='a' | c=='e' | c=='i'| c=='o' | c=='u')
        {

            vowelCount++;
        }
    }
    printf("%d",vowelCount);
    return 0;
}

A: There are several issues in your code:

*

*You parenthesized your loop condition incorrectly - it should be while ((c=getc(file))!=EOF)

*You used | instead of || inside the if condition

*You did not check the return value of fopen: if the function fails because the file is not there or for any other reasons, it returns NULL. Trying to pass that NULL to fgetc leads to a crash.

It is the last item that is probably leading to the crash. Make sure that the file test.txt is in the directory in which you are running your program.
Demo.

A: check if file == NULL.
file=fopen("test.txt","r");
if (file == NULL) {
    return -1;
}

This could very much happen if file is not present in the current directory. So specify the path of the file correctly from where exactly you need to read the file.
For example:
file = fopen ("/home/xpeng/test.txt", "r");

Make sure that the file exists.
Then it should be all right.


text:
Q: file_put_contents(C:\xampp\htdocs\instant\storage\framework/sessions/FF): failed to open stream: No such file or directory I was trying to upload this instance on Amazon elasticBeanstalk, but it doesn't seem to work.
I have tried using ssh to access the files to no avail.
i did php artisan config:cache and composer dump-autoload before uploading.
Any help is appreciated.

A: Open terminal in your project directory and run this cmd:
php artisan config:clear

A: How did I solve this issue? After running those commands and not getting the solution.
composer dump-autoload
composer install
php artisan cache:clear
php artisan config:clear
php artisan optimize
php artisan clear-compiled

The issue was simple. In my case under storage/framework there is sessions folder is missing so I created the directory and run the command again. And issue solved.
**Note: In some cases if your run php artisan cache:clear and php artisan config:clear. Your issue will be solved.
Hope this thread will solve your issue.
Happy Coding :)

A: Go to directory laravel/bootstrap/cache and delete config.php file.

A: run php artisan vendor:publish
Asking Which provider or tag's files would you like to publish?:
Type 0
Then run php artisan serve

A: Can try using php artisan optimize. This will clear everything that cache your projects.
Let me know if this help you guys. Thanks!

A: This command work in my case: php artisan config: clear

A: It worked for me when i changed all paths in C:\xampp\htdocs...\bootstrap\cache\config.php


text:
Q: HTML5/razor how to alter length of a input text box Why has html5 changed so much stuff!
How do i alter the width of the below two text boxes?

          @Html.TextBoxFor(m => m.S1_LandLine)
          @Html.ValidationMessageFor(m => m.S1_LandLine)

and
  <input type="text" id="myinput" value="1" class="Q" data-id2="Q" />

and
<select id="S1_TitleID" name="S1_TitleID">
       <option selected="selected" value="1">Mr</option>
       <option value="2">Miss</option>
       <option value="3">Mrs</option>
</select>

A: Using CSS:
.editor-field input[type="text"], .editor-field select
{
  width:100px;
}

A: To generate the desired markup:
@Html.TextBoxFor(m => m.S1_LandLine, new { data_id2 = "Q", @class = "Q" })

As far as the length is concerned (whatever that means) you could use CSS to specify the Q rule => nothing really related to ASP.NET MVC nor HTML5.

A: What exactly did HTML5 change?! I am going to assume by length you mean the maxlength, or the number of characters you can input into the text box. I may be wrong but your question is a bit ambiguous.
For the first you can do:

    @Html.TextBoxFor(m => m.S1_LandLine, new { maxlength = 10 })
    @Html.ValidationMessageFor(m => m.S1_LandLine)

And the second:
<input type="text" id="myinput" value="1" class="Q" data-id2="Q" maxlength="10" />

If you are not looking the maxlength then what are you looking?
EDIT: Just noticed you say the width, if so follow others advice on here.

A: I know i am a little off topic, but if you're looking for maxlength attribute :
We are using the MVC pattern : your view should be strongly typed to your model.
View

    @Html.LabelFor(model => model.Rating)

    @Html.EditorFor(model => model.Rating)
    @Html.ValidationMessageFor(model => model.Rating)

    @Html.LabelFor(model => model.Body)

    @Html.EditorFor(model => model.Body)
    @Html.ValidationMessageFor(model => model.Body)

And in the model, we can set defined conditions :
[Required]
[Range(1,10,ErrorMessage="Not in the 1-10 Range"]
public int Rating { get; set; }

[Required]
[StringLength(1024,ErrorMessage="Incorrect format")]
public string Body { get; set; }


text:
Q: Convert View block to helper method I have an Each/do block in my view currently, but I'd prefer to push this code into a helper, as I need to add a few conditional statements in there so I don't want to clutter up my view. Here is the view I have currently that I have been trying to code as a helper method with no luck so far
<% update.voters_who_voted.each do |voter| %>
  <%= link_to profile_path(voter) do %>
    <%= thirty_avatar(voter) %>
  <% end %>
<% end %>

How would this translate into a helper with this name
def find_voters_who_voted(update)
  ...
  ...
end

I've tried this with no luck
def find_voters_who_voted(update)
  update.voters_who_voted.each do |voter|
    link_to profile_path(voter) do
      thirty_avatar(voter)
    end
  end
end

A: Remember that all you are doing is displaying the return value of this method. It looks like you are expecting it to act as if it's part of the view, but that's not the way helpers work. Something like this would return the equivalent of your original code block
def find_voters_who_voted(update)
  update.voters_who_voted.collect do |voter|
    link_to profile_path(voter) do
      thirty_avatar(voter)
    end
  end.join
end


text:
Q: Confusion with NSDate I am trying trying to get a create an object of NSDate this way
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   // [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit  | NSMinuteCalendarUnit)fromDate:[NSDate date]];
    NSInteger day    = [weekdayComponents day];
    NSInteger month  = [weekdayComponents month];
    NSInteger year   = [weekdayComponents year];

    NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
    [timeZoneComps setDay:day];
    [timeZoneComps setMonth:month];
    [timeZoneComps setYear:year];
    [timeZoneComps setHour:00];
    [timeZoneComps setMinute:00];
    [timeZoneComps setSecond:01];

    m_currentDate         = [gregorian dateFromComponents:timeZoneComps];

When I log the currentDate, I get this
"2014-07-07 06:00:01 +0000"

If  I save this to plist I get this
07-Jul-2014 11:30:01 am

If I use "UTC" as the time zone
I get it as
"2014-07-07 00:00:01 +0000"

and inside plist it shows as
07-Jul-2014 5:30:01 am

I am not understanding what is going on, Can anybody help me out with this
I want to know, if I dont set any timeZone what timeZone will be used?
Do we need to explicitly set UTC as timeZone or we need to use systemTimeZone.

A: The thing you need to realise about NSDate is that there is no such thing as day, week, month, year, timezone, etc...
An NSDate is purely a point in time. It has no information about what time zone it is etc...
Effectively it is just a number. You can think of it as using UTC if that helps.
The classes that give you things like time zone are NSCalendar, NSDateFormatter, etc...
I'm guessing you're in a timezone of UTC+6? Thats why when you create a date with 00:00:01 and you log it out then it displays as 06:00:01.
This is nothing to do with the NSDate. What you are seeing in the console is a string. It is a representation of the date object using the default time zone (your own).
I'd have to see you code for saving to a plist but I suspect this is the same problem. You are saving something and assuming it is using a particular time zone when in reality it isn't.


text:
Q: Python Selenium find Sibling Element after the correct table is found there are multiple Tables on the Site with changing IDs, only the active one is Clickable, so i am test like this for the correct one:
def table_test(text):
    rows = driver.find_elements(By.XPATH, '//table/tbody/tr/td[2]')
    for row in rows:
        if row.text == text:
            try:
                row.click()
                break
            except:
                pass

So far this Code works, maybe there is a nicer way for this?
My Main Question is:
Each table on the Site got an Selection Field after, how can i identify the correct Selection Field also with changing IDs, after the correct table is found? Can't use the same Method due each Selection Field is useable even it is not the active one.
When i try to find the next Select Field after i found the correct Row, the first Selection Field in the Document is found - so the wrong one.
element = row.find_element(By.XPATH, '//following-sibling::select')


text:
Q: NSDateFormatter dateFromString returns nil for "2015-11-20 13:42:00.000000" I know there are many similar questions but I can't figure out my problem.
I want to convert a String like "2015-11-20 13:42:00.000000" to NSDate.
My code is like below.
let date:String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
if let value = row["date"]?.asString() {
    date = value
    let formattedDate = dateFormatter.dateFromString(date) // formattedDate is nil
}

A: You need to update your dateFormat with following
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"

As uppercase S represents fraction of second.
More detail about DateTime Format table is available here

A: Please secure your code by saving ponies !
let date = "2015-11-20 13:42:00.000000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
if let fornmattedDate = dateFormatter.dateFromString(date) as NSDate {
print ("The formated date is \(fornmattedDate)")
} else {
     print ("\(date) is not a valid date")
}

A: Try like this :-
    let date = "2015-11-20 13:42:00.000000"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
    let fornmattedDate = dateFormatter.dateFromString(date) as NSDate!
    print ("The formated date is \(fornmattedDate)")

Output:-
    The formated date is 2015-11-20 21:42:00 +0000


text:
Q: Python docx add_paragraph() inserts leading newline I'm able to use a paragraph object to select font size, color, bold, etc. within a table cell. But, add_paragraph() seems to always insert a leading \n into the cell and this messes up the formatting on some tables.
If I just use the cell.text('') method it doesn't insert this newline but then I can't control the text attributes.
Is there a way to eliminate this leading newline?
Here is my function:
def add_table_cell(table, row, col, text, fontSize=8, r=0, g=0, b=0, width=-1):
    cell = table.cell(row,col)
    if (width!=-1):
    cell.width = Inches(width)
    para = cell.add_paragraph(style=None)
    para.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run = para.add_run(text)
    run.bold = False
    run.font.size = Pt(fontSize)
    run.font.color.type == MSO_COLOR_TYPE.RGB
    run.font.color.rgb = RGBColor(r, g, b)

A: I tried the following and it worked out for me. Not sure if is the best approach:
cells[0].text = 'Some text'   #Write the text to the cell
#Modify the paragraph alignment, first paragraph
cells[0].paragraphs[0].paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER

A: The solution that I find is to use text attribute instead of add_paragraph() but than use add_run():
row_cells[0].text = ''
row_cells[0].paragraphs[0].add_run('Total').bold = True
row_cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT

A: I've look through the documentation of cell, and it's not the problem of add_paragraph(). The problem is when you having a cell, by default, it will have a paragraph inside it.

class docx.table._Cell:

paragraphs: ... By default, a new cell contains a single paragraph. Read-only

Therefore, if you want to add paragraphs in the first row of cell, you should first delete the default paragraph first. Since python-docx don't have paragraph.delete(), you can use the function mention in this github issue: feature: Paragraph.delete()
def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None

Therefore, you should do something like:
cell = table.cell(0,0)
paragraph = cell.paragraphs[0]
delete_paragraph(paragraph)
paragraph = cell.add_paragraph('text you want to add', style='style you want')

Update at 10/8/2022
Sorry, the above approach is kinda unnecessary.
It's much intuitive to edit the default paragraph instead of first deleting it and add it back.
For the function add_table_cell, just replace the para = cell.paragraphs[0]
and para.style = None, the para.style = None is not necessary as it should be default value for a new paragraph.

A: Here is what worked for me. I don't call add_paragraph(). I just reference the first paragraph with this call -> para = cell.paragraphs[0].  Everything else after that is the usual api calls.
table = doc.add_table( rows=1, cols=3 )   #   bar codes

for tableRow in table.rows:
    for cell in tableRow.cells:
        para = cell.paragraphs[0]
        run = para.add_run( "*" + specIDStr + "*" )
        font = run.font
        font.name = 'Free 3 of 9'
        font.size = Pt( 20 )

        run = para.add_run( "\n" + specIDStr
            + "\n" + firstName + " " + lastName
            + "\tDOB: " + dob )
        font = run.font
        font.name = 'Arial'
        font.size = Pt( 8 )