text:
Q: How to create UITableView programmatically I have the following code to create a view with a table programmatically
- (void) createView:(UIViewController*)viewController{
    _thisViewController = viewController;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;

    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"Title";
    titleLabel.frame = CGRectMake(75, 20, 200, 50);
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [titleLabel.font fontWithSize: 24];

    UILabel *subtitleLabel = [[UILabel alloc] init];
    subtitleLabel.text = @"Subtitle";
    subtitleLabel.frame = CGRectMake(75, 50, 400, 50);
    subtitleLabel.textColor = [UIColor blackColor];
    subtitleLabel.font = [subtitleLabel.font fontWithSize: 20];

    UILabel *labelStatus = [[UILabel alloc] init];
    labelStatus.text = @"";
    labelStatus.frame = CGRectMake(75, screenHeight - 290, 500, 50);
    labelStatus.textColor = [UIColor blueColor];
    labelStatus.font = [labelStatus.font fontWithSize: 20];

    UITableView *tableDeviceList = [[UITableView alloc] init];
    tableDeviceList.frame = CGRectMake(75, 100, screenWidth -250, screenHeight - 400);
    tableDeviceList.dataSource = self;
    tableDeviceList.delegate = self;

    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancelButton setTitle:@"Cancelar" forState:UIControlStateNormal];
    [cancelButton sizeToFit];

    cancelButton.frame = CGRectMake((screenWidth/2)-100, screenHeight - 250, 100, 50);
    cancelButton.backgroundColor = UIColorFromRGB(0x066D8B);
    cancelButton.layer.cornerRadius = 20;
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    UIViewController *viewControllerModal = [[UIViewController alloc] init];

    UIView *nooView = [[UIView alloc] initWithFrame:CGRectMake(50, 80, screenWidth - 100, screenHeight - 160)];
    nooView.backgroundColor = UIColorFromRGB(0xE8E8E8);
    nooView.layer.cornerRadius = 20;

    [nooView addSubview:titleLabel];
    [nooView addSubview:subtitleLabel];
    [nooView addSubview:tableDeviceList];
    [nooView addSubview:labelStatus];
    [nooView addSubview:cancelButton];

    [viewControllerModal.view addSubview:nooView];

    [viewController presentViewController: viewControllerModal animated:YES completion:nil];
}

Which is throwing me an error of tableView:numberOfRowsInSection:, so I wonder if is there a way to add a function to a UITableView created this way (I'm creating my UITableView programmatically).
Also, my class is of type NSObject, so I wonder if there will be a problem with the assignment of the dataSource and delegate properties of the tableDeviceList.

A: You need to implement the dataSource and delegate methods of UITableView in your class,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; // number of sections
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10; // should be your array count
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellId = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.textlabel.text = @"test";
    return cell;
}

A: Firstly, you should set the following:
    UITableView(your tableview name).delegate = self;
    UITableView(your tableview name).dataSource = self;

Secondly, you need to implement the delegate methods and datasource methods
such as:


text:
Q: Laravel Elixir - Compiling and concatenating bootstrap files with a custom file name Trying to concatenate the bootstrap folder into a single .scss file but its not working.
It either puts them into a file called "all.scss" or if I try to specify the output name:
mix.styles([
    'bootstrap/*.scss'
], 'resources/assets/sass/bootstrap.scss', 'resources/assets/sass/');

It created a directory called 'bootstrap.scss' and then puts an all.scss file into that.
How can I concatenate all the files in the bootstrap folder into a single scss file with my name of choice?

A: Presumably because your mixing css files, if you want to do scss files (or sass) you need to do:
mix.sass([
 'bootstrap/*.scss'
], 'resources/assets/sass/'name of choice'.scss');

Also, it might be worth mentioning, you probably want to put the output file in public folder. So something like this:
'public/vendor/`name of choice`.scss'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex working in Regex101 not in R Here is my regular expression:
https://regex101.com/r/UjWanf/1
(^\d+?\.?\d{0,2})([A-Za-z]+|\s[A-Za-z]+)

Escaped for R:
"(^\\d+?\\.?\\d{0,2})([A-Za-z]+|\\s[A-Za-z]+)"

Everything seems to be working fine in regex101 but when I apply the same pattern using strapplyc function in R, it does not capture the entire string.
Example strings:
50ml tomato sauce
5g chillies
5 Units tartar sauce
0.25 Units pasta sauce

I want to pick up 50ml, 5g, 5 Units and 0.25 Units respectively.
In R, when I apply the pattern in the regex link above using strapplyc from the library gsubfn, my output is 50m, 5g, 5 U, 0.25 U. Here is a sample of my code:
    a=c("ingredient1", ingredient2", "ingredient3", "ingredient4")
    b=c("50ml tomato sauce", "5g chillies", "5 Units tartar sauce", "0.25 Units
    pasta sauce")
    consolidated <- data.frame(a,b)`
library(gsubfn)
pattern_reg2 <- "(^\\d+?\\.?\\d{0,2})(\\s?[A-Za-z]+)"
consolidated$c <- strapplyc(consolidated$b, pattern_reg2)
#c column with the desired results

Any suggestions?

A: I'm not familiar with strapplyc, but it looks like it's not working properly. Have you tried using R's base regex functions?
library(RCurl)
#Load this webpage into a string so I can match the patterns you listed
test_file <- getURL("https://stackoverflow.com/questions/48798279/regex-working-in-regex101-not-in-r")
rgx = "(\\d+?\\.?\\d{0,2})([A-Za-z]+|\\s[A-Za-z]+)" #removed the ^ to allow whole string matching
rgx_result <- gregexpr(rgx,test_file)
result <- regmatches(test_file, rgx_result)
result[[1]][317:321] #only the answers from the strings you were asking to match

returns:
[1] "50ml"     "5g"       "5 Units"  "25 Units" "50ml"

And that works properly. Is there any reason you needed to use strapplyc?
Added example for working in a list:
test_list <- list('50ml tomato sauce','5g chillies',
           '5 Units tartar sauce',
           '0.25 Units pasta sauce')
for(i in 1:length(test_list)) {
    rgx_result <- gregexpr(rgx,test_list[[i]])
    print(regmatches(test_list[[i]], rgx_result))
}

I'm sure this can be done more cleanly with an apply function, but I'm just not very good with those.


text:
Q: Google protobuf: if I add field from one side will it break another one? I have two micro services. First service encodes messages using google protobuf (google docs) and sends to second one. Second one decodes this message and uses the data.
Now I need to add a field to this message object. If I do it at one side only will it break another side?
For example, if I add something to json this will break nothing. Is it really the same with google protobuf?

A: From the docs (see here: https://developers.google.com/protocol-buffers/docs/overview):

You can add new fields to your message formats without breaking backwards-compatibility; old binaries simply ignore the new field when parsing. So if you have a communications protocol that uses protocol buffers as its data format, you can extend your protocol without having to worry about breaking existing code.

A: Cited from Goole Protobuf documentation on extending the Protobuf from here:

*

*you must not change the tag numbers of any existing fields.

*you must not add or delete any required fields.

*you may delete optional or repeated fields.

*you may add new optional or repeated fields but you must use fresh tag numbers (i.e. tag numbers that were never used in this protocol buffer, not even by deleted fields).

In your case, if your change on one side did not violate any of the above rules, it will not break the other side.


text:
Q: Webkit CSS Transition fails on float property change Hit an annoying bug in Webkit browsers, where CSS transitions aren't fired if you alter the float property. Here's a Fiddle to demonstrate: http://jsfiddle.net/patrickmarabeas/RxeWc/
Essentially, if you look to have a transition when an element's width changes, but also alter float: left; to float: none;, the transition simply doesn't fire. This causes further issues when you are intending on calling some JS on transition end:
$('#element').one('transitionend webkitTransitionEnd oTransitionEnd otransitionend', function(){
    ...
}

I am applying a class changing the elements float property prior to the width alteration, and have tried both:
$(this).toggleClass('removeFloat widthChange');

//and

$(this).toggleClass('removeFloat');
$(this).toggleClass('widthChange');

I've hit this problem due to the need to use white-space: nowrap; in one particular instance of layout - which doesn't work with floated elements.

A: Typical SO session, spend an hour figuring out the root problem, search SO for a solution, find none, carefully construct question with example Fiddle while continuing to try every possible suggestion someone might come up with, and as a result solve your own problem. Thought it was odd ball enough to post anyway though.
Simply needed to examine the elements CSS after setting it, and prior to adjusting its width:
$(this).toggleClass('removeFloat');
$(this).css('float'); //or any other valid property
$(this).toggleClass('widthChange');

See this updated Fiddle: http://jsfiddle.net/patrickmarabeas/vrcaA/

Edit: Chrome looks to fixed the issue


text:
Q: Getting a Color from a String input I am making an application where at some point i need the user to select a color, but as to not just have 50 radioButtons, I was wondering if it is possible to actually get the color they want from a textfield or something.

A: Why don't you use a JColorChooser that is a standard Swing component?
You can read a tutorial here but it is quite straightforward to use, as every Swing dialog, the result is something like:

A: Wouldn't it be easier to just make a JComboBox or something alike?
But to answer your question: Yes it is possible. I'll give a piece of code that you could use as a start to get you going (assuming you still want the string to color)
String text = "red";
Color color;
Field field = Class.forName("java.awt.Color").getField(text.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
color = (Color)field.get(null);

A: Try using Color.parseColor(text);

A: you can always use a select box.
info on how to create a JComboBox

A: TRy
Color aColor   = (Color) Color.class.getField("white").get(null);

ALso,
See if the static method Color.decode() will serve your purpose.


text:
Q: How to mount /usr at boot time without an initramfs? I'm having trouble booting into my system with systemd installed. I wouldn't like to use an initramfs, so I use a self-configured kernel which starts my kernel with the following in-built command line:
root=/dev/sda1 init=/usr/lib/systemd/systemd

But it will obviously not work, as the /usr is not yet mounted at this time. How can I make this work?

A: Quite simple... don't separate / and /usr anymore. It's a pointless headache. If you have a partition for everything, / will be a nearly empty filesystem anyway. Merge them into one.
Example for merging / into /usr:
mount /dev/sda1 /mnt/root
mount /dev/sda2 /mnt/usr
cp -a /mnt/root/usr /mnt/usr/usr
mv /mnt/usr/* /mnt/usr/usr/
cp -a /mnt/root/. /mnt/usr/.

Finally change the cmdline to root=/dev/sda2. Don't forget to adapt your /etc/fstab accordingly.


text:
Q: Create an array of consecutive numbers from 1 to n in C? I'm trying to code a function that will make an array of consecutive numbers from 1 up to a number n. For example, I would expect array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}. My code doesn't seem to be running but I don't exactly know why.
int count (int a)
{
   scanf("%d", &a);
   int i;
   int array[a];
   do
   {
      i = 0;
      a = a - i;
      array[a - 1] = a;
      i++;
   }
   while (a > 0);
   printf("Resulting array is %d", array[a]);
   return 0;
}

A: An idiomatic C way would be to define a function that fills an existing array:
void count(int *array, int max)
{
    for (int i = 0; i < max; ++i)
    {
        array[i] = i+1;
    }
}

You can call it e.g. like this:
int arr[10];
count(arr, 10);
for (int i = 0; i < 10; ++i)
{
    printf("%d ", arr[i]);
}

A: You should use a for loop to create your array.
int i;
int array[a];
for(i = 0; i < a; i++) {
  array[i] = i + 1;
}

return 0;

A: Your do while loop could simply be replaced by the following for loop:
for (i = 0; i < a; i++)
  array[i] = i + 1;

Similarly, for displaying each element in array, you can iterate over the elements of array by means of a for loop:
for (i = 0; i < a; i++)
  printf("Element at %2d is %d\n", i, array[i]);

A: First and foremost, the print statement
 printf("Resulting array is %d", array[a]);

is wrong!! That's not how you print an array. You need to loop over the index, get the individual elements and print them.
Moreover, when you try using array[a], think of the value for a. That's surely not what you want.
That said, there are other issues, like setting i to 0 in each iteration of do...while loop. That will lose the previously calculated value and start over. Move the initial assignment outside the loop body.
A slightly modified version, follow the comments
#include  <stdio.h>

int count (void)                 // no need for parameter if you're asking user for size
{
   int size = 0;                 //define size
   int ret = scanf("%d", &size); //read it

   if ( (ret != 1) || ( size < 1) ) return -1;      //error check

   int i = 0;                    //initialize local variables

   int array[size];              //note: this is VLA

   do
   {
       array[i] = i+1;           //start populating elements
       i++;
   }
   while (size > i);             //go on unless you've reached the given size

   puts ("Resulting array is");   // start printing ....

   for (i = 0; i < size; i++)
   {
       printf("%d\t", array[i]);   //...them one by one
   }

   return 0;
}

int main(void)
{
    (void)count();  //call the function
}

A: Try something like this:
int* count(int a)
{
   int array[a];
   for (int i = 0; i < a; ++i)
   {
      array[i] = i + 1;
   }
   for (int i = 0; i < a; ++i)
   {
      printf("%d, ", i + 1);
   }
   return array;
}

A: Just use a simple "for" loop:
for (i = 0; i < a; i++)
    {
    array [i] = i + 1;
    }

A: *

*You don't really need the a parameter. You can use a local

*the do,while is broken because you set i to 0 at each iteration and its overly complicated. You can achieve the same result in a much easier way. An element at location i has to have value i+1, easy as it sounds.

*You have to loop over the element of the array to print them all. A single printf prints only 1 element of the array. If you want them all, then you have to iterate over all of them.

What about something like the following?
void count(){
   int a,i=0;
   scanf("%d", &a);
   int array[a];
   while(i<a){
    array[i]=i+1;
    i++
   }

   //now print it
   i=0;
   while(i<a)
    printf(" %d ", array[i++]);

}

As an aside, note that you are using VLAs. That means there's a limit on the size of the array you can create which depends on your machine+compiler.

A: So there are a few bugs here . One that if you are accepting 'a' as a arg to function , why are you scanning it then. It just over writes the value you collected. Two the way you are trying to print the array is wrong as specified above and you should use a loop.  Three , you can save a few lines like ,
for(int i =0; i<a ; i++)
{
arr[i]=i+1;
 }

A:
I'm trying to code a function that will make an array of consecutive
  numbers from 1 up to a number n.

In C++ there is already such a function that is named iota and declared in the header <numeric>.
In C such a function can look the following way
void iota(int a[], size_t n, int value)
{
    for (size_t i = 0; i < n; i++) a[i] = value++;
}

Here is a demonstrative program
#include <stdio.h>

void iota(int a[], size_t n, int value)
{
    for (size_t i = 0; i < n; i++) a[i] = value++;
}

int main(void)
{
    size_t n = 1;

    scanf( "%zu", &n );

    int a[n];

    iota( a, n, 1 );

    for ( size_t i =0; i < n; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    return 0;
}

If to enter 10 then the output will look like
1 2 3 4 5 6 7 8 9 10

As for your program then in this loop
do
{
    i = 0;
    a = a - i;
    array[a - 1] = a;
    i++;
}
while (a > 0);

the variable a is not being changed because in the beginning of each iteration the variable i is set to 0.
You could write the loop like
i = 0;
do
{
    array[a - i - 1] = a - i;
    i++;
} while ( i != a );

Take into account that this statement
printf("Resulting array is %d", array[a]);

does not make sense. If you are going to output an array element by element you have to use a loop as for example it is shown in the demonstrative program above.


text:
Q: How does server identify frames in case of multiple VLAN sub-interfaces? When I create a VLAN sub-interface in Linux, then it gets the same MAC address as its parent interface. For example with ip link add link eth0 name eth0.333 type vlan id 333 command, the eth0.333 gets the same MAC as eth0. Am I correct that server identifies received frames based on VLAN tag or if the VLAN tag is missing, then the frame from the switch is to eth0 itself?

A: The default behavior is to add a interface that will only accept packets where the 802.1q field is the same as the vlan id to this given interface.
In a very simplified way, the Mac address will be the same as the parent, so the packet is delivered to the phy interface, and processed by the kernel, searching for a 802.1q Tag field that is right after the source mac address field. This field will be identified with the 0x8100 EtherType. The last 12 bits define the vlan id.

This Ethernet frame will have the tag removed and delivered to the vlan interface. You can double-check this using tcpdump on both interfaces and pinging an ip address of eth0.333. You shall see output only on eth0:
# tcpdump -ni eth0 vlan 333
# tcpdump -ni eth0.333 vlan 333

The default behavior on the opposite traffic direction will be tag and deliver(can be configured).
If you want to create virtual interfaces with a Mac Address that is different from the parent, you will have to use the macvlan option of iputils2. Remember that your switches could have some mac related restrictions and block traffic from this newly created interface.
And yes, you are correct. If there is no tag the traffic will be delivered to your physical interface. Your configurations will define if the packet will be accepted.


text:
Q: Экспорт и импорт данных из 1 колонки в MySQL Добрый вечер.
Есть интернет-магазин, несколько тысяч товаров. Есть таблица products в БД MySQL, соответственно.
Задача: нужно изменить описание у каждого товара. Надо выгрузить данные из 1 поля description в какой то удобно редактируемый вид с возможностью дальнейшего импорта обратно.
Возможно ли это?
A: Чтобы не съехали описания при расчете просто на порядок строк, я бы вывел, как минимум, две колонки: id, описание.
Эти данные в csv или даже Excel отдаёте Васе-фрилансеру для перевода, тёте Маше для литературной правки и т.п. Результат трудов затем импортируете простеньким скриптом, который пробежит по каждой строчке, обновляя в базе опсиание по id. Или испортируете в новую временную таблицу, и обновляете основную по ключу.


text:
Q: What does the command "timeout" do in Windows? While looking for the screen timeout settings, I typed "timeout" in the search menu and a
timeout run command option appeared.
I clicked it out of curiosity but nothing seemed to happen and a search was not helpful.

A: You can execute timeout /? on command prompt to see what this command do along with options available.

This utility accepts a timeout parameter to wait for the specified time period (in seconds) or until any key is pressed. It also accepts a parameter to ignore the key press.

More information with examples can be found here.

A: You can use Timeout command in Windows to stop the execution for some time and then continue. you can specify the number of seconds to wait, it would wait till the time elapses or until user presses any key.
For example:
C:\>Timeout 10

Windows will pause the execution for 10 seconds, you may press a key to continue.
Another similar command is Sleep command.
Windows provides a resource kit tool Sleep which can be used in batch files or command prompt to stop the execution and wait for some time.
C:\>Sleep 50  or C:\>Sleep -m 50

N.B. Timeout can be set through the Batch file also.


text:
Q: Laravel Eloquent relationship mapping issue with three tables and belongsTo() function I have three tables (instances, users, user_instance).  Each user can be assigned to one instance.  A instance can have many different users.
I try to get the instance_id of from the instance a particular user is assigned to by using Laravel 5.1 Eloquent and belongsTo() function, by calling $this->user->instance->instance_id.
No matter what I've tried, I'm always getting a NULL result in my AuthController.php:
DB Schema:
    mysql> show columns from instances;
    +------------+------------------+------+-----+---------+----------------+
    | Field      | Type             | Null | Key | Default | Extra          |
    +------------+------------------+------+-----+---------+----------------+
    | id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | name       | varchar(150)     | NO   |     | NULL    |                |
    | key        | varchar(150)     | NO   |     | NULL    |                |
    | created_at | int(11)          | NO   |     | NULL    |                |
    | updated_at | int(11)          | NO   |     | NULL    |                |
    +------------+------------------+------+-----+---------+----------------+

    mysql> show columns from users;
    +----------------+---------------------+------+-----+---------+----------------+
    | Field          | Type                | Null | Key | Default | Extra          |
    +----------------+---------------------+------+-----+---------+----------------+
    | id             | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
    | first_name     | varchar(50)         | YES  |     | NULL    |                |
    | last_name      | varchar(50)         | YES  |     | NULL    |                |
    | email          | varchar(100)        | NO   |     | NULL    |                |
    | password       | varchar(255)        | NO   |     | NULL    |                |
    | salt           | varchar(255)        | YES  |     | NULL    |                |
    | remember_token | varchar(255)        | YES  |     | NULL    |                |
    | created_at     | int(10) unsigned    | NO   |     | NULL    |                |
    | updated_at     | int(10)             | NO   |     | NULL    |                |
    | last_login     | int(10) unsigned    | YES  |     | NULL    |                |
    | ip_address     | varchar(15)         | NO   |     | NULL    |                |
    | timezone       | int(10)             | YES  |     | NULL    |                |
    | active         | tinyint(1) unsigned | YES  |     | NULL    |                |
    +----------------+---------------------+------+-----+---------+----------------+

    mysql> show columns from user_instance;
    +-------------+------------------+------+-----+---------+----------------+
    | Field       | Type             | Null | Key | Default | Extra          |
    +-------------+------------------+------+-----+---------+----------------+
    | id          | int(10) unsigned | YES  | PRI | NULL    | auto_increment |
    | user_id     | int(10) unsigned | NO   |     | NULL    |                |
    | instance_id | int(10) unsigned | NO   |     | NULL    |                |
    | created_at  | int(11)          | NO   |     | NULL    |                |
    | updated_at  | int(11)          | NO   |     | NULL    |                |
    +-------------+------------------+------+-----+---------+----------------+

App/Controllers/AuthController.php
    <?php
    use App\Models\User;
    use App\Models\Instance;
    use App\Models\User_Instance;
    class AuthController extends Controller {
    ...
    die($this->user->instance); // Returns: NULL
    ...
    }
    ?>

App/Models/Instance.php
    <?php namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class Instance extends Model
    {
        /**
         * Indicates if the model should be timestamped.
         *
         * @var bool
         */
        public $timestamps = true;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'instances';

        /**
         * The tables primary key.
         *
         * @var string
         */
        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = ['name', 'key', 'created_at', 'updated_at'];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = [];
    }
    ?>

App/Models/User_Instance.php
    <?php namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class User_Instance extends Model
    {
        /**
         * Indicates if the model should be timestamped.
         *
         * @var bool
         */
        public $timestamps = true;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'user_instance';

        /**
         * The tables primary key.
         *
         * @var string
         */
        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = ['user_id', 'instance_id', 'created_at', 'updated_at'];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = [];
    }
    ?>

App/Models/User.php
    <?php namespace App\Models;

    use Illuminate\Auth\Authenticatable;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Auth\Passwords\CanResetPassword;
    use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
    use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
    use Zizaco\Entrust\Traits\EntrustUserTrait;

    class User extends Model implements AuthenticatableContract, CanResetPasswordContract
    {
        use Authenticatable, CanResetPassword, EntrustUserTrait;

        /**
         * Indicates if the model should be timestamped.
         *
         * @var bool
         */
        public $timestamps = true;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'users';

        /**
         * The tables primary key.
         *
         * @var string
         */
        protected $primaryKey = 'id';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'first_name',
            'last_name',
            'email',
            'password',
            'salt',
            'remember_token',
            'created_at',
            'updated_at',
            'last_login',
            'ip_address',
            'timezone',
            'active'
            ];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = ['password', 'remember_token'];

        /**
         * Map the instance with the user.
         *
         * @var int
         */
        public function instance()
        {
            return $this->belongsTo('App\Models\User_Instance');
        }
    }
    ?>

A: public function instance()
{
 return $this->belongsTo('App\Models\User_Instance');
}

belongsTo , in above method,specifically apply the where condition using snakecase (i.e. instance_id) ..but in your case that would result in wrong result or no result at all ( you want to map on user_id)
As the Laravel - Eloquent suggest .
 if the foreign key on the parent model is not snakecase name (instance_id), you may pass a custom key name as the second argument to the belongsTo method:
return $this->belongsTo('App\Models\User_Instance','user_id');

>>laravel relations


text:
Q: Moving Down the Background Image in Mobile I want to move the background image lower in @media screen and (max-width: 660px) because every time I change the screen size it moves up the background image. What I want is everytime I change to smaller screen size the image will goes down to fill some spaces.

@import url('https://fonts.googleapis.com/css?family=Roboto|Modak|Poppins|Ubuntu&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-image: url(https://i.ibb.co/xhgZz0F/bg-image.jpg);
  background-repeat: no-repeat;
  background-size: cover;
}

a {
  text-decoration: none;
}

header {
  position: relative;
  min-height: 13vh;
  min-width: 100vw;
  /* background-color:#000; */
}

.logo {
  position: absolute;
  width: 120px;
  height: 45px;
  border-radius: 10px;
  background-color: #E73A15;
  top: 30%;
  left: 2%;
  color: #fff;
  text-transform: uppercase;
  font-family: 'Ubuntu', sans-serif;
  font-size: 2.5em;
  text-align: center;
}

.social {
  position: absolute;
  top: 30%;
  left: 20%;
  width: 250px;
  height: 45px;
  /* background-color: black; */
}

ul {
  position: relative;
  top: 18%;
}

.social ul li {
  display: inline-block;
  list-style-type: none;
  color: #fff;
  padding: 12px 6px;
  text-align: center;
}

.faceb,
.linked,
.git {
  position: relative;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  background-color: #E73A15;
  text-align: center;
}

.centerIcon {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#menu {
  margin: 2.2rem 3rem 0 0;
  float: right;
  clear: both;
}

#menu ul li {
  display: inline-block;
  list-style-type: none;
  padding: .5rem .8rem;
  margin: 0 .3rem;
  text-align: center;
  font-size: .7rem;
  font-weight: 900;
  text-transform: uppercase;
}

#menu .nav a {
  font-family: "Roboto", sans-serif;
  color: #fff;
}

.nav {
  background: rgb(209, 129, 129);
  background: linear-gradient(118deg, rgba(209, 129, 129, 1) 0%, rgba(217, 81, 52, 1) 35%, rgba(231, 58, 21, 1) 100%);
  border-radius: 50px;
}

@media screen and (max-width: 1200px) {}

@media screen and (max-width: 660px) {
  body {
    background: url(https://i.ibb.co/xhgZz0F/bg-image.jpg) no-repeat center center fixed;
    background-size: auto;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  }
  .social {
    display: none;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <title>Jury Gregorio | Design for Everyone</title>

Jury

About

Contact

A: Add
background-position: center bottom;

you can also add px instead of the words
Play around with the values that fits best for you.

A: You can use this code

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <title>Jury Gregorio | Design for Everyone</title>

Jury

About

Contact


text:
Q: Text appearing bold on some pages with images
Possible Duplicate:
Why are some pages in my PDF coming out bold?

For some reason, all the text on certain pages is appearing bold when there is a picture on the same page. I saw the other similar questions and tried converting the images firstly to PNGs with no transparency but that didn't fix it. I then tried converting them to JPEGs which didn't work either. Finally I converted them to EPS which also didn't fix the issue.
I am using Lyx and Xetex. I am viewing the file using Adobe Reader 10 on Windows 7. Below is an example of one the pages which comes out bold:
\begin{figure}
\noindent \centering{}\includegraphics[width=330pt]
{ReportImg/projectedmarkermodel}
\caption{Example showing the projected marker corners based around the marker with ID 0\label
{fig:Example-showing-the} }
\end{figure}

\subsubsection{Objective function}

We first needed to define the new objective function to minimise.
The objective function will...

The whole page comes out bold. I tried printing the page as well, it appears bold when printed.
EDIT: I don't think this is the same problem as previous questions, I have tried all the solutions given as answers before but the result is the same. I have even tried different PDF viewers and it still appears bold.

A: I had such an issue when mixing pages with images with and without transparency. If you experience this in Acrobat Reader (almost all including recent versions), but not other PDF readers, the following code in the preamble might do the trick and enforce the same RGB rendering for all pages (for xelatex):
\usepackage{eso-pic}
\AddToShipoutPicture{%
\makeatletter%
\special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceRGB>> >>}%
\makeatother%
}

For pdflatex use:
\pdfpageattr {/Group << /S /Transparency /I true /CS /DeviceRGB>>}


text:
Q: Datetimes in Python I have two dates
'2017-03-10 19:01:27'
'2017-03-11 07:35:55'

I would like to get the difference one day. How can I do this with the time zone in mind?
Because the time zone of these dates is not known to us. I'm new in Python
I have:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

date_first = datetime.strptime(args[0], time_format)
date_second = datetime.strptime(args[1], time_format)

rep_date_first = date_first.replace(tzinfo=from_zone)
rep_date_second = date_second.replace(tzinfo=from_zone)

timezone_date_first = rep_date_first.astimezone(to_zone)
timezone_date_second = rep_date_second.astimezone(to_zone)

day = timezone_date_first.day - timezone_date_second.day

day return me 0, How to fix it? Please help me

A: By changing the timezone you're probably adding or subtracting enough hours to your dates that they end up on the same day. You should probably just assume a timezone as you're converting them from strings – or just leave them naive datetime objects.
>>> d1 = '2017-03-10 19:01:27'
>>> d2 = '2017-03-11 07:35:55'
>>> date_first = datetime.strptime(d1, '%Y-%m-%d %H:%M:%S')
>>> date_second = datetime.strptime(d2, '%Y-%m-%d %H:%M:%S')
>>> date_first.day
10
>>> date_second.day - date_first.day
1

A: arrow module is a big friend to everyone working with dates, you achive a shift very easily.
import arrow
dt = arrow.get('2017-03-10 19:01:27')
dt = dt.replace(tzinfo='Europe/Warsaw')
dt2 = dt.shift(days=-1)
assert dt2.isoformat() == '2017-03-09T19:01:27+01:00'

What you are asking a bit amigous: I would like to get the difference one day and your code is not runnable in isolation (args[0]), but I think you can assume the dates are in the same timezone.


text:
Q: C++ how to use std::function with overloaded operators of different return types I'm trying to use the standard std::function with custom overloaded operators. However applying std::logical_and to my Test class with a string parameter is not working in this situation.
class Test {
public:
    std::string value;

    Test(std::string cvalue) : value(cvalue) {}

    std::string operator&& (const std::string& rhs) const {
        if (rhs == value) {
            return "true";
        }
        return "false";
    }
};

int main() {
    Test test("hey");
    std::string out = std::logical_and<std::string>()(test, "hey");
    std::cout << out << std::endl;
    return 0;
}

What is the proper way of achieving this? My expected output is "true"

A: You need to use std::logical_and<> to allow deduction for both arguments and return type:
std::string out = std::logical_and<>()(test, "hey");

Demo


text:
Q: Swift Core Data, record won't delete, even with save() I'm attempting to delete an object from the core data in swift. I am able to save objects fine, however, the delete does not work. I am calling both .delete(object) and then .save() which run correctly and have verified that the object being fed in is valid, however the object never get's deleted despite no errors coming back from the code.
Here's my save function, when false is provided as a parameter, it should delete the record:
func SaveFighter(_ save:Bool)
{
    // get the (only) managed context...
    let managedContext = DataBaseHelper.persistentContainer.viewContext
    // ... get the Entity (table) description for the only entity [SavedFighter]...
    let entity = NSEntityDescription.entity(forEntityName: "SavedFighter", in: managedContext)!
    // ... retrieve the associated Maanaged Object for this entity
    let savedFighter = NSManagedObject(entity: entity, insertInto: managedContext)

    // put Fighter object members into matching attributes in the Managed Object
    savedFighter.setValue(self.nickname, forKeyPath: "nickname")
    savedFighter.setValue(self.first_name, forKeyPath: "first_name")
    savedFighter.setValue(self.last_name, forKeyPath: "last_name")
    savedFighter.setValue(self.weight_class, forKeyPath: "weight_class")
    savedFighter.setValue(self.statid, forKeyPath: "statid")
    savedFighter.setValue(self.losses, forKeyPath: "losses")
    savedFighter.setValue(self.draws, forKeyPath: "draws")
    savedFighter.setValue(self.wins, forKeyPath: "wins")
    savedFighter.setValue(self.id, forKeyPath: "id")
    savedFighter.setValue(self.title_holder, forKeyPath: "title_holder")
    savedFighter.setValue(self.fighter_status, forKeyPath: "fighter_status")
    savedFighter.setValue(self.rank, forKeyPath: "rank")
    savedFighter.setValue(self.thumbnail, forKeyPath: "thumbnail")

    if (save) // save this fighter in DB
    {
        // need to account for exceptions if saving fails
        do
        {
            // commit the prepares Managed Object in the Managed Context
            try managedContext.save()
            // set flag to say the object has been saved to DB
            print("Fighter: \(first_name) was ADDED to the Bookmarks Database!")
        }
        catch let error as NSError
        {
            print("Could not save \(first_name) \(error)")
        }
    }
    else  // delete this fighter from bookmarks DB
    {
        // create a fetchrequest to associate with the SavedFighter entity
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SavedFighter")
        // set a predicate (query) to only select a unique record based on id
        print("Attempting to delete record with ID: " + String(self.id))

        fetchRequest.predicate = NSPredicate(format: "id = %@", String(self.id))   // use id because it is unique

        do
        {
            // run the query to get the resultset (can be more than one record)
            let resultData = try managedContext.fetch(fetchRequest) as! [SavedFighter]
            print("Found \(resultData.count) records to delete...")
            // iterate through all the found records...
            for object in resultData
            {   //... to delete each record
                print(object)
                managedContext.delete(object)
                try managedContext.save() // commit changes to context
            }
        }
        catch
        {
            print("Could not find any records to delete...")
        }
    }
}

I'm expecting when Fighter.SaveFighter(false) is called for the object to be deleted from the DB, however it remains no matter what.
From the debug, I've got the following prints:
Attempting to delete record with ID: 1161
Found 1 records to delete...
<SavedFighter: 0x61800028c170> (entity: SavedFighter; id: 0xd000000000bc0000 <x-coredata://64D235C6-E488-4EC1-ADA6-9F4B7CBCAB0D/SavedFighter/p47> ; data: <fault>)

So the object is clearly being retrieved from the DB successfully, but still won't delete.


text:
Q: javascript code executing after submit I have some javascript code that is being executed before pressing submit button ,even the html form is not displayed.
What I want is to fill out a form and  these data input will be used in the controller.After that what is returned from  the controller will be used  in the javascript function.
I do not know why it doesn't work.
this is my code
@model highchart.Models.model2

  <form Action="Index" method="post">

     taux de change:"

    <input name="taux" value="EUR/USD" />
    <input type="text" id="txtId">

        Date_début
        Date_fin

          <input type="Date" name="date_début" id="date_début" value="@(Request.Form[" date_début "])"/>

          <input type="Date" name="date_fin" id="date_fin" value="@(Request.Form[" date_fin "])"/>

    <input type="submit" value="AFFICHE" name="affiche" onclick="storeInSession()" />
  </form>


text:
Q: Mysql query WHERE column is in json array I have setup an query where it selects multiple things.
$stm = $db->query('SELECT startUser, forUser, percentage, time, taskTitle, taskDesc, color FROM admin_task WHERE forUser = "'.$queryanswer.'")');

But for user is like this in the DB:
["demo","   user"]

How can I check if forUser (the json array above) has demo? can i even check this?

A: If it truly is a JSON field, in 5.7 you can do this:
SELECT
  startUser,
  forUser,
  percentage,
  time,
  taskTitle,
  taskDesc,
  color
FROM admin_task
WHERE JSON_CONTAINS(forUser->'$[*]', JSON_ARRAY("somestring"))

A: I think you can achieve this only in Mysql 5.7.
In version 5.7 you can do something like:
SELECT JSON_EXTRACT(json_field, '$.name');

and it will extract only the name key from json object.
Search all items with the 'JavaScript' tag:
SELECT * FROM `table` WHERE JSON_CONTAINS(json_field, '["JavaScript"]');

Find all items with tags starting 'Java':
SELECT * FROM `table` WHERE JSON_SEARCH(json_field, 'one', 'Java%') IS NOT NULL;

use 'one' to find the first match or 'all' to find all matches
You can extract the Twitter nickname using a JSON path:
SELECT name, json_field->"$.twitter" AS `twitter` FROM `user`;

You can also reference a JSON path in the WHERE clause to only return users with a Twitter account:
SELECT name, profile->"$.twitter" AS `twitter` FROM `user` WHERE profile->"$.twitter" IS NOT NULL;

You can do more things like:

*

*Creating JSON Values

*Normalization, Merging, and Autowrapping of JSON Values

*Searching and Modifying JSON Values

*Comparison and Ordering of JSON Values

*Aggregation of JSON Values
for more info please refer to: https://dev.mysql.com/doc/refman/5.7/en/json.html

A: SELECT startUser,
forUser,
percentage,
time,
taskTitle,
taskDesc,
color
FROM admin_task WHERE JSON_SEARCH(forUser -> '$[*]', 'one', 'demo');


text:
Q: my observable not returning data inspite of getting it from mongodb I am new to angular and node. Just completed the tutorial given in angular quickstart 'Tour of Heroes'. This works perfectly. But instead of using in memory web api as in the tutorial I want to modify it to get data from mongo db. So I modified my hero.service.ts to get the data from mongodb/express. But I get no data at all. And no error as well. I am stuck here. Would appreciate any help.
This is the function getHeroes from hero.service.ts.
getHeroes(): Observable<Hero[]> {
            return this.http.get(this.heroesUrl)
                       .map(response => response.json().data as Hero)
                       .catch((error : Response | any) => {
                             return Observable.throw(error.statusText);
                        });
}

In the dashboard component I subscribe to it as follows:
export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private heroService: HeroService) { }

   ngOnInit(): void {
     this.heroService.getHeroes()
     .subscribe(heroes => this.heroes = heroes.slice(1, 5));
     // console.log("angular heroes",this.heroes );
   }
  }

Also here I get a typeerror for slice saying it cannot slice an undefined. but if I make it this.heroes.slice(1,5) it does not give error.
On the server side I have heroes.js. Here I get the data from mongo db which works fine.I can see that it has retrieved the list of heroes from database.
//Get All Heroes
 router.get('/heroes', function(req,res,next){
          db.heroes.find(function(err,heroes){
          if(err){
              res.send(err);
          }
          console.log("heroes:" , heroes);
          res.json(heroes);
         });
 });

08/08/2017:
 I modified my observable code as follows:
    getHeroes(): Observable<Hero[]> {
             return this.http.get(this.heroesUrl)
             .map(response => {
                  console.log('heroes',response.json());
                   response.json() as Hero[];
     })
     .catch((error : Response | any) => {
             return Observable.throw(error.statusText);
      });
    }

I removed response.json().data (because it was giving undefined in console.log,any idea why?) and made it response.json(). Now it shows me the heroes in console. But it does not make it till the subscription.


text:
Q: Passing a variable from a list as part of calling a function I am using SimpleSalesforce and would like to use the describe() function. An example of that is sf.Contact.describe() to describe the Contact record. I would like to loop through several records in a list, but I'm not sure how to pass in a variable in place of Contact.
Objects = ['Contact','Opportunity']
for object in Objects:
    print sf.object.describe()

This yields an error of:
simple_salesforce.api.SalesforceResourceNotFound: Resource object Not Found. Response content: [{u'errorCode': u'NOT_FOUND', u'message': u'The requested resource does not exist'}]

A: object is a string in this example. You can retrieve the attribute using getattr
Objects = ["Contact", "Opportunity"]
for object in Objects: # object is a string.
    print getattr(sf, object).describe()

A: You can make a list of objects instead of a list of strings, then you can invoke the describe method off of those objects
Objects = [sf.Contact, sf.Opportunity]
for object in Objects:
    print object.describe()

A: Objects = ['Contact','Opportunity']
for object in Objects:
    if object == 'Contact':
        print sf.Contact.describe()
    elif object == 'Opportunity':
        print sf.Opportunity.describe()


text:
Q: Past Perfect (Progressive) problem I was helping my nephew with some homework but this time I reached my limit. I am not quite sure what the correct answer is here or even if there is only one good answer. One has to finish the sentence:

The police asked him, "Did you see who caused the accident?"
They asked him if he had seen who...

The sentence should finish in Simple Past Perfect, I assume.
I would say:

... has caused the accident.

I spent one year in the USA and my English skills were never a problem for me, but my grammar is a bit rusty. From what I have read online I think we should exchange the "has" for "had".

A: It should either be simple past, ie. who caused the accident, or past perfect, which is who had caused the accident.
To quote English Page:

The past perfect is a verb tense which is used to show that an action took place once or many times before another point in the past.

In this case, it is clear that the seeing of the accident took place before the police's asking the man. Since the police "asked" the man(in the past), and the accident happened before that, the criterion for using the past perfect is met.
Source: https://www.englishpage.com/verbpage/pastperfect.html


text:
Q: How to create portable applications? In Ubuntu can you create a portable application and have it work on an OS like SUSE 10.x via USB stick? I'm not sure if this can be done or not, how to do it or if it would be compatible; any advice is greatly welcomed.
I need to make a portable version of Stellarium and have it work in SUSE 10.x. I haven't been able to make portable Linux versions. I'm pretty sure there can be portable versions of applications since you can run a program like TOR on it.

A: You can take a look at the Portable Linux Apps site, which has a decent collection of portable applications that you can carry in a USB drive and use it on any Linux based OS without worrying about installing dependencies.
Regarding your specific question, you can probably open a thread in their forum and request them to create a portable version of Stellarium.
Or you can take a look at the documentation provided at the site regarding creating portable apps but honestly, it didn't make much sense to me.


text:
Q: Where to get Visual Studio CD images? My Visual Studio 2005 CD (Standard) is broken and I have to install it to me new PC. I tried downloading "pirated" ISOs, but they have illegal keys pre-pidded to the setup (cannot be changed). So where can I get the original images with which I can use my own cd-key?

A: You can get it in MSDN (if you have an account) or in MSDNAA (for students, if the university provides access). Visual Studio 2010 Beta is still free, but be sure to read its license! You can't release anything that you produced with the Beta version. (At least that's what the license of the alpha version said.)

A: Try calling Microsoft and seeing if they have a replacement policy. Maybe if you send them back the broken disc, they'll send you a new one.

A: I found an answer: I can use the downloaded ISOs, copy the files to my HDD and change the product key from \Setup\Setup.SDB file.
Here's where I got the answer from.


text:
Q: Laravel push collection to empty array Hey I have a query where I'm getting a site, once i get the site i manually setAttribute a key companies and its value is [], I then want push multiple arrays inside the companies empty array one at a time based on their condition if the condition is true the array will be pushed if not it won't be pushed. In this case the second if statement override the data of first statement, i want to keep both data. i tried using put() function but it throws an error Method Illuminate\Database\Query\Builder::put does not exist.
can anyone please help me out. thanks
Code:
        $site =  CpdApi::where('id', $admin->id)->get();

        $allData = collect([$site->first()->setAttribute('companies', [])]);

        if(count($abcApiData))
        {
            $allData->first()->companies = $abcApiCompanies;
        }

        if(count($localStandardCompaniesQuery))
        {
            $allData->first()->companies = $localStandardCompaniesQuery->pluck('companies');
        }

        return $allData;

Data Structure of Site:
[
    {
        "id": 7,
        "title": "Just Testing",
        "email": "testing@testing.co.uk",
    }
]

Data Structure of abcAPIData and localStandardCompaniesQuery:
[
    {
        "comp_id": 94,
        "comp_title": "Loreum Ipseum 01",
    },
    {
        "comp_id": 245,
        "comp_title": "Loreum Ipseum 02",
    }
]

A: Ok, so i've figured it out on my own. This is what i did, if anyone has a better option please post you answer. Thankyou.
$site =  CpdApi::where('id', $admin->id)->get();

$companies = collect([]);

if(count($localAdvanceCompaniesQuery))
{
    $companies = $companies->merge($localAdvanceCompaniesQuery->pluck('companies'));
}

if(count($localStandardCompaniesQuery))
{
    $companies = $companies->merge($localStandardCompaniesQuery->pluck('companies'));
}

if(count($mapleApiData))
{
    $companies = $companies->merge($mapleApiCompaniesQuery->pluck('companies'));
}

if(count($atpApiData))
{
    $companies = $companies->merge($atpApiCompaniesQuery->pluck('companies'));
}

$companiesFlattened = $companies->collapse();
$allData = collect([$site->first()->setAttribute('companies', $companiesFlattened)]);


text:
Q: less / css selector values based on selectors from import file outside my control @seven-phases-max  I have refactored my code a few times based mostly on your answers to my stackoverflow.com posts but would like to get your feedback to my latest and hopefully final variation:
Ultimately I ended up using :extend to get copies of css properties of styles not under my control:
Below is example of approach I've used in several places create css from base css/less selectors defined in less files outside of my control and optionally over-ridden in another less file outside my control:
.CODE-COLORING-ICON {opacity: 0.0};

Below code works works with and w/o above css / mixin line
.CodeMirror-gutters:before,
.CodeMirror-gutters:hover:after {
    &:extend(.CODE-COLORING-ICON);
}

In other places, I created created empty selectors fearing less would not like an extend like above with ".CODE-COLORING-ICON" not defined.  I was surprised the above code worked.
The end game is to merge css from theme with override values from another file.


text:
Q: Loading handsontable with local data fails I am trying to use http://jsfiddle.net/kc11/y66uc1cq/ to load some data which I have included into a handsontable view. Although the JS is valid:
$(document).ready(function () {

    function getCarData() {
        return [
        ["Nissan", 2009, "black", "black"], ["Nissan", 2006, "blue", "blue"], ["Chrysler", 2004, "yellow", "black"], ["Volvo", 2012, "white", "gray"]];
    }

    var data = [
        ["", "Kia", "Nissan", "Toyota", "Honda"],
        ["2008", 10, 11, 12, 13],
        ["2009", 20, 11, 14, 13],
        ["2010", 30, 15, 12, 13]
    ];

    $("#example1").handsontable({
        data: data,
        minRows: 5,
        minCols: 6,
        minSpareRows: 1,
        currentRowClassName: 'currentRow',
        currentColClassName: 'currentCol',
        autoWrapRow: true,
        rowHeaders: true,
        colHeaders: true
    });

    $("#example1").handsontable('selectCell', 3, 3);

});

The load is not occurring. Why and how can I fix this?

A: Hard to test since all the references in the fiddle are broken, but try this:
var table = new Handsontable($("#example1"), {
    data: data,
    minRows: 5,
    minCols: 6,
    minSpareRows: 1,
    currentRowClassName: 'currentRow',
    currentColClassName: 'currentCol',
    autoWrapRow: true,
    rowHeaders: true,
    colHeaders: true
});
table.render();

Source: http://handsontable.com/demo/understanding_reference.html


text:
Q: Create a popup in Rust using Windows APIs I would like to create a dialog box or popup in Rust in a similar fashion to PowerShell.
I'm struggling to find documentation on the Windows APIs for this. The closest I've found so far is the CreateDialogA macro (Rust winapi equivalent).
I've found some things on it such as Creating a New Dialog Box (C++), but most of it is not applicable to a Rust project.
Perhaps dialoge template is relevant?

A: main.rs
extern crate winapi;

use std::ptr::null_mut as NULL;
use winapi::um::winuser;

fn main() {
    let l_msg: Vec<u16> = "Wassa wassa wassup\0".encode_utf16().collect();
    let l_title: Vec<u16> = "\u{20BF}itconnect\0".encode_utf16().collect();

    unsafe {
        winuser::MessageBoxW(NULL(), l_msg.as_ptr(), l_title.as_ptr(), winuser::MB_OK | winuser::MB_ICONINFORMATION);
    }
}

This uses the MessageBoxW function.
The argument winuser::MB_OK can be winuser::MB_OK, winuser::MB_OKCANCEL, winuser::MB_ABORTRETRYIGNORE, winuser::MB_YESNOCANCEL, winuser::MB_YESNO, winuser::MB_RETRYCANCEL or winuser::MB_CANCELTRYCONTINUE.
The argument winuser::MB_ICONINFORMATION can be winuser::MB_ICONHAND, winuser::MB_ICONQUESTION, winuser:: MB_ICONEXCLAMATION or winuser::MB_ICONASTERISK.
Cargo.toml should include:
[dependencies.winapi]
version = "0.3"
features = ["winuser"]


text: Q: Using radio buttons with 2-way-binding and iteration in ractive.js I wonder if it is possible to use ractive.js' 2-way-binding with a nested iteration section. What I need is to iterate over the answerOptions for each calibration. My template looks like this:


text:
Q: MVC Multiple submit buttons and downloading a file - is this the only way? I have an ASP.NET MVC application which has a view with a bunch of search criteria, and Search and Export buttons.
In order to make the site nice to use, and minimize the number of database hits, I'd like the users to be able to set the search criteria then hit either Search to get the results on screen (using an Ajax form) or Export directly to Excel. The key here is that both buttons are in an AJAX form in the view, and both perform a submit action so that the underlying actions in the controller receive the form fields.
I already have the exporting to Excel working - the file is created and written to a MemoryStream, and the action returns the memory stream. I have tested this using a separate button which doesn't do a submit and the file is returned correctly - however I do not have access to the parameters when doing a normal post.
Using this answer to another SO question, I have implemented multiple submit buttons and they both execute their respective actions correctly, and both get the form fields. However, because the action for the export file returns a MemoryStream, I receive an error as it is unable to parse the data (the page is expecting something which can be rendered by the browser).
I have adapted a work around for this which I found here, but it isn't one I'm very happy with due to the following flaws:

*

*Two requests are made when exporting: one to create the file, then another to retrieve the file.

*Clicking Export after doing a Search loses the search results (due to
the InsertionMode set to replace). This will require another work
around to swap the InsertionMode based on which button is clicked.

*Having to store the MemoryStream in the session (even if it is only
temporary).

*Returning a script block from the Export action.

It generally feels like a bit of a hack, and I feel like there must be a tidier way to achieve the same result.
Here's a breakdown of the code I have:
My View (using bootstrap):
@using (Ajax.BeginForm("Summary", "MyController", null,
    new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "result-scs",
        OnBegin = "submitFormBegin(xhr, 'form-scs', '" + Url.Content("~/Content/Images/Loading.gif") + "')",
        OnFailure = "submitFormFailure(xhr, status, error, 'form-scs', '" + Url.Action("Login", "Account") + "')",
        OnComplete = "submitFormComplete(xhr, status, 'form-scs')"
    },
    new { id = "form-scs" }))
{
    @Html.AntiForgeryToken()

            Field1:
            @Html.DropDownList("field1", (IEnumerable<SelectListItem>)ViewBag.field1, "All", new { id = "", @class = "form-control input-sm multiselect" })

            Field2:
            @Html.ListBox("field2", (IEnumerable<SelectListItem>)ViewBag.field2, new { id = "", @class = "form-control input-sm multiselect" })

            Field3:
            @Html.ListBox("field3", (IEnumerable<SelectListItem>)ViewBag.field3, new { id = "", @class = "form-control input-sm multiselect" })

                <button type="submit" value="Search" name="action:Search" class="btn btn-sm btn-primary" data-loading-text="Loading...">Search</button>

                <button type="submit" value="Export" name="action:Export" class="btn btn-sm btn-primary" data-loading-text="Loading...">Export</button>

}

My Controller:
[ValidateAntiForgeryToken]
[MultiButton(MethodType="action", Argument="Search")]
public ActionResult Search(int? field1 = null,
  int[] field2 = null, int[] field3 = null)
{
  if (Request.IsAjaxRequest())
  {
    var model = Repository.List(field1, field2, field3);
    return View(model);
  }
  else
  {
    throw new HttpException(404, "Resource unavailable.");
  }
}

[MultiButton(MethodType = "action", Argument = "Export")]
public ActionResult Export(int? field1 = null,
  int[] field2 = null, int[] field3 = null)
{
  MemoryStream stream = Repository.GetExportStream(field1, field2, field3);
  string filename = "Export" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  Session[filename] = stream;
  return Content("");
}

public ActionResult GetFile(string filename)
{
  MemoryStream ms = (MemoryStream)Session[filename];
  Session[filename] = null;
  return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Export.xlsx");
}

MultiButtonAttribute (to allow multiple buttons to submit to different actions):
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string MethodType { get; set; }

    public string Argument { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
    {
        bool isValidName = false;
        keyValue = String.Format("{0}:{1}", MethodType, Argument);
        ValueProviderResult value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[MethodType] = Argument;
            isValidName = true;
        }

        return isValidName;
    }
}

Is there are better way to achieve the same result? Maybe a way to obtain all the forms fields without doing a submit?


text:
Q: Восстановление байтовой информации (uint8_t) из хекса (hex) Для переносимости ключи шифрования представляются из массива uint8_t в шестнадцатиричном виде:
for(int i = 0; i < KEYSIZE; ++i)
    std::cout << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(PrivateKey[i]);

В силу специфики hex'а, каждый байт информации представляется двумя символами, т.е. из одного байта выходит целых два. Как корректно прочитать стринг с хексом в массив uint8_t, чтобы восстановить оригинальную байтовую информацию?
Убил около пяти часов, пытаясь осуществить задачу в виде reinterpret_cast<const uint8_t*>(publicKey.c_str()), пока не догадался, что проблема в изложенном выше феномене, а не в каких-то других частях кода. Но с ними, если что, потом ;)

A: Например, можно воспользоваться std::from_chars():
#include <iostream>
#include <charconv>
#include <string>

int main()
{
    std::string str = "ff01aa00";

    for (std::size_t i = 0; i < str.size(); i += 2)
    {
        int val = -256;
        std::from_chars(&str[i], &str[i+2], val, 16);
        std::cout << val << " ";
    }
}

Вывод:
255 1 170 0


text:
Q: Upgrade to Magento 2.3 to Magento 2.4.4 with Peral theme I am a beginner on magento (I have no experience)
I'm switching from magento 2.3 to magento 2.4, I used this link for the update: https://blog.magezon.com/magento-2-3-to-2-4-upgrade/
when I compile or when I switch to prod mode I have a

Fatal error:  Declaration of WeltPixel\Backend\Model\Logger::info($message, array $context = Array) must be compatible with Monolog\Logger::info($message, array $context = Array): void in /home/ps41711-1757/www/luzaka-m2-preprod/app/code/WeltPixel/Backend/Model/Logger.php on line 57.

   public function info($message, array $context = array())
    {
        $result = $this->_parseLogMessage($message, $context);
        if ($result !== false) {
            return parent::info($message, $context);
        }
        return $result;
    }

I also updated the theme (Peral Weltpixel)
Does anyone know what to do in this case please?


text:
Q: How to position nested Tbox in top right? How to position the smaller nested box, so it appeared in the top right corner (see image below)?

Here is my current, wrong implementation:
\newcommand\TBox[3][]{%
  \tikz\node[draw,ultra thick,text width=#2,align=left,#1] {#3};}

\TBox{14cm}{%
  \TBox{10cm}{xxx \vspace{9cm}} \TBox{3cm} \\
  }

A: It would be better to place all your boxes in a single tikzpicture, because right now you are nesting them which is in general not a good idea.
To come back to your original question, you can use baseline=(current bounding box.north) to top align the boxes:
\documentclass{article}

\usepackage{tikz}

\newcommand\TBox[3][]{%
  \tikz\node[draw,ultra thick,text width=#2,align=left,#1,baseline=(current bounding box.north)] {#3};}

\begin{document}

\TBox{14cm}{%
  \TBox{10cm}{xxx \vspace{9cm}} \TBox{3cm} \\
  }

\end{document}


text:
Q: Qt application crashes on exit, OS applies "fault tolerant heap shim" I can't isolate what is causing the application to crash on exit. What adds further confusion is that it doesn't always crash, sometimes it does, sometimes it doesn't and it seems to be completely arbitrary.
The sample basically crates a custom image provider that loads a static google maps API request as a PNG image to show in QML. The image provider itself works, I first suspected that the issue might be with instantiating the network access manager on the stack, but that's not it, I get the same behavior instantiating it dynamically. Funny thing is the crash doesn't seem to correspond to anything in particular. Just starting and closing the app sometimes generates the crash, without any interaction with it, but it mostly doesn't crash without any interaction. Sometimes multiple interactions with the map center and zoom result in no crash on exit, but most of the time it does.
Another suspect is the event loop I instantiate in order to "block" the image provider method while the network request is completed. Due to the design of the image provider, the image must be returned by the same method that requests it, in other words I cannot use the "recommended" approach of just launching the request from a method and capturing it with connecting its completed signal to another method. But that doesn't seem to be it either, as the provider always manages to provide the image I assume there is no problem with it. At least not directly, but maybe some side effect of the network access?
BTW Qt is spewing out some warnings, only on the first network access manager use. With Qt 5.2 I only got those four:
QSslSocket: cannot resolve TLSv1_1_client_method
QSslSocket: cannot resolve TLSv1_2_client_method
QSslSocket: cannot resolve TLSv1_1_server_method
QSslSocket: cannot resolve TLSv1_2_server_method
QSslSocket: cannot resolve SSL_select_next_proto

... and after upgrading to the fresh 5.3.1 in hopes of removing those warnings actually two more appeared in addition to the previous four:
QSslSocket: cannot resolve SSL_CTX_set_next_proto_select_cb
QSslSocket: cannot resolve SSL_get0_next_proto_negotiated

Maybe those warnings are somehow related to the crash?
Here is also the appcrash info:
  Fault Module Name:    ntdll.dll
  Fault Module Version: 6.1.7601.17725
  Fault Module Timestamp:   4ec49b8f
  Exception Code:   c0000005
  Exception Offset: 000332a0
  OS Version:   6.1.7601.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Platform info: Windows 7 x64, stock 32bit Qt build with GCC
Here is the relevant code:
C++
class MapReader : public QQuickImageProvider {
public:
    explicit MapReader() : QQuickImageProvider(QQuickImageProvider::Pixmap, QQmlImageProviderBase::ForceAsynchronousImageLoading) { }

    QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) {
        QNetworkAccessManager m;
        Q_UNUSED(requestedSize)
        Q_UNUSED(size)
        QEventLoop loop;
        QObject::connect(&m, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
        QNetworkReply * r = m.get(QNetworkRequest(QUrl(id)));
        loop.exec();

        if (r->error()) {
            qDebug() << "Error: " << r->errorString();
            r->deleteLater();
            return QPixmap();
        }

        QPixmap p;
        p.loadFromData(r->readAll());
        r->deleteLater();
        return p;
    }
};

QML
Rectangle {
    id: root
    width: 360
    height: 360

    property string url : 'image://map/http://maps.googleapis.com/maps/api/staticmap?center=' + n + ',' + e + '&zoom=' + zoom.value + '&size=' + width  + "x" + height + '&maptype=satellite'
    property real n : 48.858222
    property real e : 2.2945

    Timer {
        id: t
        repeat: false
        interval: 100
        running: false
        onTriggered: {
            placeholder.source = root.url
        }
    }

    function refresh() { if (t.running) t.restart(); else t.start() }

    Image {
        id: placeholder
        anchors.fill: parent
    }

    MouseArea {
        anchors.fill: parent

        onClicked: {
            var xOffset = (mouseX / width - 0.5) * (360 / Math.pow(2, zoom.value))
            var yOffset = (mouseY / height - 0.5) * (360 / Math.pow(2, zoom.value))

            console.log(xOffset + " " + yOffset)

            root.n = root.n - yOffset
            root.e = root.e + xOffset
            root.refresh()
        }
    }

    Slider {
        id: zoom
        value: 17
        maximumValue: 21
        minimumValue: 1
        stepSize: 1
        x: 80
        y: parent.height - 25
        width: parent.width - 90

        onValueChanged: root.refresh()
    }
}

A: The problem is in your image provider class. I am not sure exactly where, but it is there, since without it I cannot reproduce the crash. I am able to tell this because the image provider in your case is entirely unnecessary - a QtQuick Image element will accept and work with the Google API url source as it is.


text:
Q: Localization issue with iOS11 Swift 4 I just built an app that is using localization with the code
let locale = NSLocale.current.languageCode

What it returns to me and the simulator is something like "zh" (For Traditional Chinese Users)
However, when I upload it to the App Store, other users using traditional Chinese has found that the localization is not working properly. (i.e. Not showing Chinese), but on my phone it works perfectly! For the same label and same page!
Does anyone has a similar problem on it?
The only possible solution I can think of is changing NSLocale to Locale, will it work?
p.s. All iOS device is running on 11.3

A: Personally I don't depend on local to return language code , I check my localized value , for example say i support 2 languages in my app i would have
fr file
"currentCode" = "fr"

en file
"currentCode" = "en"

and while the app is opened , I check what's current language selected by system with
if NSLocalizedString("currentCode",comment:"") == "fr" {
    //
}
else {
   //
}


text:
Q: data mismatch when reading .bin file in gcc compiler I want to implement FOTA in stm32,
for that I am reading . bin file in gcc compiler and send data serially to uart.
but ther is mismatch between file read and actual file.  I compare data, then i found that fread function does not read proper data, then i print data of 200 byte and compare with online .bin to hex converter and stm32programmer. I found that the problem in fread function. but how come i dont know.below is the code.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
uint8_t DATA_BUF[1024];
uint8_t APP_BIN[80000];
int main(int argc, char *argv[])
{
  int comport;
  int bdrate   = 115200;       /* 115200 baud */
  char mode[]={'8','N','1',0}; /* *-bits, No parity, 1 stop bit */
  char bin_name[1024];
  int ex = 0;
  FILE *Fptr = NULL;

  do
  {
    if( argc <= 2 )
    {
      printf("Please feed the COM PORT number and the Application Image....!!!\n");
      printf("Example: .\\etx_ota_app.exe 8 ..\\..\\Application\\Debug\\Blinky.bin");
      ex = -1;
      break;
    }

//get the COM port Number
comport = atoi(argv[1]) -1;
strcpy(bin_name, argv[2]);
  // ex = sizeof(ETX_OTA_HEADER_);
  // printf("Opening COM%d...\n", ex );
printf("Opening COM%d...\n", comport+1 );

//if( RS232_OpenComport(comport, bdrate, mode, 0) )
//{
//  printf("Can not open comport\n");
 // ex = -1;
 // break;
//}

//send OTA Start command
  //ex = send_ota_start(comport);
//if( ex < 0 )
//{
//  printf("send_ota_start Err\n");
//  break;
//}

printf("Opening Binary file : %s\n", bin_name);

Fptr = fopen(bin_name,"rb");

if( Fptr == NULL )
{
  printf("Can not open %s\n", bin_name);
  ex = -1;
  break;
}

fseek(Fptr, 0L, SEEK_END);
uint32_t app_size = ftell(Fptr);
fseek(Fptr, 0L, SEEK_SET);

printf("File size = %d\n", app_size);

//Send OTA Header
//meta_info ota_info;
//ota_info.package_size = app_size;
//ota_info.package_crc  = 0;          //TODO: Add CRC

//ex = send_ota_header( comport, &ota_info );
//if( ex < 0 )
//{
 // printf("send_ota_header Err\n");
 // break;
//}

//read the full image
if(fread( APP_BIN, 1, app_size, Fptr ) != app_size )
{
  printf("App/FW read Error\n");
  ex = -1;
  break;
}
for(uint32_t i = 0; i < 200; i++)
  {
      printf("%d  ",APP_BIN[i]);
  }
} while (false);

return(ex);
}

this one is original data when i used online .bin to hex converter
0x00, 0x00, 0x08, 0x24, 0xA1, 0x0D, 0x10, 0x08, 0xED, 0x0A, 0x10, 0x08, 0xF3, 0x0A, 0x10, 0x08,

this is the data when fread function used
0x00, 0x00, 0x08, 0x24, 0x4D, 0x0C, 0x10, 0x08, 0x99, 0x09, 0x10, 0x08, 0x9F, 0x09, 0x10, 0x08,

I could not find out what is the problem.
if someone has already faced the same, plls guide me
thanking you.

A: Using fseek and ftell to find the size of a file is an anti-pattern. It's not necessary. Here is a more correct way to read a file's binary contents.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

struct bytes_s {
  uint8_t *buf;
  size_t size;
};

/* Read file contents as unsigned bytes. */
struct bytes_s read_bytes(FILE *f) {
  size_t buf_size = 1024, size = 0;
  uint8_t *buf = malloc(buf_size * sizeof *buf);
  for (;;) {
    size_t read_size = fread(buf + size, 1, buf_size - size, f);
    if (read_size == 0) break;
    size += read_size;
    buf_size *= 2;
    buf = realloc(buf, buf_size * sizeof *buf);
  }
  return (struct bytes_s) { .buf = realloc(buf, size), .size = size };
}

int main(int argc, char **argv) {
  if (argc < 2) exit(1);
  FILE *f = fopen(argv[1], "rb");
  if (!f) exit(2);
  struct bytes_s bytes = read_bytes(f);
  for (size_t i = 0; i < bytes.size; ++i) {
    printf("%02x ", bytes.buf[i]);
    if ((i & 0xf) == 0xf) putchar('\n');
  }
  putchar('\n');
  return 0;
}

Here's a run:
$ gcc rb.c -o rb
$ ./rb rb.c
23 69 6e 63 6c 75 64 65 20 3c 73 74 64 69 6f 2e
68 3e 0a 23 69 6e 63 6c 75 64 65 20 3c 73 74 64
6c 69 62 2e 68 3e 0a 23 69 6e 63 6c 75 64 65 20
3c 73 74 64 69 6e 74 2e 68 3e 0a 0a 73 74 72 75
63 74 20 62 79 74 65 73 5f 73 20 7b 0a 20 20 75
[ rest elided ]

Now compare to Linux hex dump:
$ hexdump -C rb.c
00000000  23 69 6e 63 6c 75 64 65  20 3c 73 74 64 69 6f 2e  |#include <stdio.|
00000010  68 3e 0a 23 69 6e 63 6c  75 64 65 20 3c 73 74 64  |h>.#include <std|
00000020  6c 69 62 2e 68 3e 0a 23  69 6e 63 6c 75 64 65 20  |lib.h>.#include |
00000030  3c 73 74 64 69 6e 74 2e  68 3e 0a 0a 73 74 72 75  |<stdint.h>..stru|
00000040  63 74 20 62 79 74 65 73  5f 73 20 7b 0a 20 20 75  |ct bytes_s {.  u|
[ rest elided ]


text:
Q: How to move all occurrences of the first element of the list to the end of the list in Haskell? I want to extract the first element and all of its occurrences from a list and put them in the end of a list in Haskell
What I have now is this.
relegate [] = []
relegate (x:xs) = xs ++ [x]

With input [3 ,1 ,4 ,3 ,5 ,3 ,8] it returns me [1,4,3,5,3,8,3] but I wanted instead to return this list [1 ,4 ,5 ,8 ,3 ,3 ,3].

A: Right now you're just adding x to the end, which will only move the first occurrence, not all of them. You should instead find all equal elements, and remove them from the list. This can be done with partition in Data.List, which takes a predicate function and gets a list of elements that matches the predicate and a list that doesn't:
import Data.List

relegate :: (Eq a) => [a] -> [a]
relegate [] = []
relegate l@(x:_) = nonMatching ++ matching
    where (nonMatching, matching) = partition (/= x) l

Or, more pointfree:
import Data.List

relegate :: (Eq a) => [a] -> [a]
relegate [] = []
relegate l = uncurry (++) $ partition (/= head l) l

A: This algorithm requires to first determine that first element x, and then enumerate over the list, here we will yield all elements that are different from  x, and keep track of the number of times we have found an element that is equal to x, and when we reach the end of the list, we replicate x the number of times we encountered x in the list:
relegate :: Eq a => [a] -> [a]
relegate [] = []
relegate (x:xs) = go xs 1
    where go [] n = replicate n x
          go (y:ys) m
              | x == y = go ys (m+1)
              | otherwise = y : go ys m
This of course assumes that if x == y, then x and y are the same element. If that is not the case, you should work with an accumulator that keeps track of the equal elements.


text:
Q: UITabBarController/UINavigationController missing title I have a UINavigationController and UITabBarController visible at the same time.  Both the tab bar buttons and the navigation bar take their text from the title of the currently active view.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"View Title";

However I want the different.  In fact I'd like the navigation controller title to remain the same whichever view is being displayed.
Any ideas?
Many thanks.

A: Try This
UITabBarItem *tItem = [self tabBarItem];
[tItem setTitle:@"Title for tabbar"];

it won't change your tabbar title when you set the navigation title like
[self setTitle:@"Title for navBar"];

but I found sometimes it changes both tabBar and naviBar
then I insert the TabBar set titling code in -(void)viewWillAppear again to prevent
such happening
Thanks

A: You'll have to manually assign the title name, as you are doing above, in your other view controllers.
If your view hierarchy is more than two levels deep, be wary as the back button will look a little strange to the user (unless you override it). In fact, if every view has the same title, that may look strange to the user, period...

A:    -(void)viewDidLoad{
 [self setTitle:@"Custom Title goes here"];
}

This worked for me.

A: According to KwangBok Lee, I have tested, the best answer would be:
self.title = @"my settings";//changes both tabbars and navigationbars title

self.tabBarItem.title = @"settings";//only changes tabbars title

A: What I've found is... using
self.tabBarController.title = @"navTitle";

changes the navigation bar title, while
self.title = @"tabTitle";

changes the tab bar item title.


text:
Q: jQuery dialog doesn't close from code behind after a Response.TransmitFile My problem is that using the quoted aspx page when i call the closing Dialog from Code Behind the dialog doesn't close.
If i comment the Response Transmit file part of code then the dialog properly close, else the download starts but the dialog remains opened.
Let me know if you have some suggestions, thanks!
ASPX PAGE:
<%@ Page Async="true" AsyncTimeout="30" Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register src="CreateUI.ascx" tagname="CreateUI" tagprefix="uc1" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <%--JQuery--%>

    <link href="Styles/jquery-ui-1.10.4.css" rel="stylesheet" type="text/css" />

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <asp:ScriptManager ID="mainScriptManager" runat="server"></asp:ScriptManager>

    <uc1:CreateUI ID="CreateUIForm" runat="server" />

    <asp:Table ID="TableMain" runat="server" CssClass="table">
        <asp:TableRow ID="TableRow1" runat="server">
            <asp:TableCell ID="TableCell1" runat="server">
                <asp:HiddenField ID="UI_Paths" runat="server" />
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

        <asp:UpdatePanel ID="UpdatePanelDownload" UpdateMode="Conditional" ChildrenAsTriggers="false" runat="server">
            <ContentTemplate>
                <asp:Label ID="LabelMessage" runat="server" Text="Operation ended successfully, do you want to download the produced files?

"></asp:Label>
                <asp:Button ID="ButtonDownload" runat="server" Text="Yes" Width="50px" onclick="ButtonDownload_Click" />
                <asp:Button ID="ButtonNo" runat="server" Text="No" Width="50px" OnClientClick="closeDialog('jobDone'); return false;" />
            </ContentTemplate>
        </asp:UpdatePanel>

</asp:Content>

CODE BEHIND:
private void DownloadFile(object uiPaths)
{
    UIGEN config = (UIGEN)System.Configuration.ConfigurationManager.GetSection("UIGENGroup/UIGEN");
    string toPath = config.sharedPath;
    if (!toPath.EndsWith(@"\"))
        toPath += @"\";

    string[] fileNamePaths = uiPaths.ToString().Split(new char[] { '*' });

    string zipName = toPath + DateTime.Now.ToString().Replace("/", "_").Replace(":", "_").Replace(" ", "_") + ".zip";
    SharpZipLib.CreateZip(zipName, null, fileNamePaths, SharpZipLib.FolderOffset.LastDirOnly);

    try
    {
        FileInfo file = new FileInfo(zipName);

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/x-zip-compressed";
        Response.Flush();
        Response.TransmitFile(file.FullName);
        Response.End();
    }
    catch (System.Exception ex)
    {
        //To do ...Manage the error
    }

    //Delete zip from Server Shared Folder
    if (File.Exists(zipName))
        File.Delete(zipName);
}

protected void ButtonDownload_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        DownloadFile(UI_Paths.Values);
    }

    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), UniqueID, "closeDialog('jobDone');", true);
}

A: I found the solution by myself.
The problem is that Response.End(); End the response before the resisted javascrip in ButtonDownload_Click is executed.
I tried the suggested solution (read in other similar threads) to change Response.End() into context.ApplicationInstance.CompleteRequest() but the download doesn't start that way.
So i deleted:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), UniqueID, "closeDialog('jobDone');", true);

from ButtonDownload_Click and i modified the aspx page from this:
<asp:Button ID="ButtonDownload" runat="server" Text="Yes" Width="50px" onclick="ButtonDownload_Click" />

to this:
<asp:Button ID="ButtonDownload" runat="server" Text="Yes" Width="50px" OnClientClick="closeDialog('jobDone');" onclick="ButtonDownload_Click" />

This way the ButtonDownload suddenly close the dialog from javascript then execute the server side ButtonDownload_Click performing the download.


text:
Q: How can I query these 4 tables by joining them? Could someone help me and teach me to query this. Please..
Pawner table

Item table

loan_assignment table

Loan table

When I join those 4 tables the result should be like this

I had queried this but the result is redundant.
This is my query:
SELECT a.date_loan_granted, p.pawner_id, p.name, c.item_name, l.principal_loan
FROM loan_assignment a
JOIN pawner p ON p.pawner_id = a.pawner_id
JOIN item c ON c.item_id = a.item_id
JOIN loan l ON l.loan_id = a.loan_id;

The result of this query above ^ is this

A: To fix your issue: In loan_assignment set the loan_id for 500 to 1 and 300 to 2. then on loan the value that is null for payment set the loan_id to 1 and the one with 200 set the loan_id to 2. should clear up your issue once you use distinct.
Your parent child relationship for these tables goes as follows
Pawner
PK: Pawner_ID
FK: Pawnshop_ID

Loan_assignment
PK: None
FK: Pawnshop_ID, Pawner_ID, Item_ID, Loan_ID

Item
PK: Item_ID

Loan
PK: Loan_ID

Right now structure should be:
A Pawn Shop can have multiple pawners.
A Pawner can have multiple loans.
A Loan can have one or many items.
An Item can have multiple payments.

here are some suggestions to fix your tables since using a distinct is not good enough to resolve your structure issue.
Loan Assignment: all loans belong to a pawnshop and a pawner (why not just have them belong to a pawner and remove the pawnshop since that information is redundant and can be found from the parent child relationship). This table needs its own primary key because each loan is treated different. This table should have the inital loan in it with the amount all the rest of the transactions that your trying to do here should be moved to a payment table with a PK of its own and a FK back to the loan it belongs to.
Item Table: The Item_ID field is the primary key for this table. the values need to be unique because each item is a piece of inventory you need to treat separate. you may want a FK in this table linking it back to the Loan Assignment so that a loan can have multiple items assigned to it.
Loan: this table needs to have some information moved to the loan table and some moved to the suggested payment table.
The table structure is not solid for what you would like to do. i recommend at this point going online and looking at the parent child relationship for a loan or pawn shop database that exists and working from that.

A: I think this would do it for you, althought, NOTE* i belive you are missing a column from your description of the table LOAN_Assignment (pawner_id)
SELECT a.date_loan_granted, p.pawner_id, p.name, c.item_name, l.principal_loan
FROM loan_assignment a
JOIN loan l ON l.loan_id = a.loan_id;
JOIN pawner p ON p.pawner_id = l.pawner_id
JOIN item c ON c.item_id = a.item_id


text:
Q: Python - Take the index of slightly different values I am interested to take the index of a generic list "L" of values contained in another list, called "target". It seems simple, but if I have the target list with slightly different values, I do not know how to consider this difference. For instance, if in the "L" list I have a value that is 1.9, and in the target the value is 1.89, I want to take the index of 1.9, since it is close to 1.89. How can I do this?
L = [0.4,0.5,0.55,0.78,0.9,1.1,1.8,1.9]
target = [0.55,0.9,1.09,1.89]
index = []
for i in target:
    index.append(L.index(i))
print(index)

Expected output: [2,4,5,7]
Thanks in advance!

A: You could use math.isclose:
import math

L = [0.4, 0.5, 0.55, 0.78, 0.9, 1.1, 1.8, 1.9]
target = [0.55, 0.9, 1.09, 1.89]

index = [i for i, e in enumerate(L) if any(math.isclose(e, t, abs_tol=0.05) for t in target)]
print(index)

Output
[2, 4, 5, 7]

The computational complexity of the above approach is O(nm), where n and m are the lengths of the lists L and target. Additionally you could sort target to do it in O((n + m)logn):
def is_close_to_any(e, tgt):
    import bisect
    """Finds if any values are close in O(log n)"""
    point_before_insertion = max(0, bisect.bisect(tgt, e) - 1)

    # find two closest points
    values = tgt[point_before_insertion:point_before_insertion + 2]

    # return if any of the two is close
    return any(math.isclose(e, t, abs_tol=0.05) for t in values)

target = sorted(target)
index = [i for i, e in enumerate(L) if is_close_to_any(e, target)]
print(index)

Output (using sorted and bisect)
[2, 4, 5, 7]

A: If L is sorted, you can use bisect to find the closest value:
from bisect import bisect

def find_closest(L, x):
    index = bisect(L, x)

    if index == 0: return 0
    elif index == len(L): return index-1
    elif x - L[index-1] > L[index] - x: return index
    else: return index-1

[find_closest(L, x) for x in target]
# [2, 4, 5, 7]

A: Python's min of the abs distance over zipped values and indices.
L = [0.4,0.5,0.55,0.78,0.9,1.1,1.8,1.9]
target = [0.55,0.9,1.09,1.89]

[min(zip(L, range(len(L))), key=lambda x:abs(x[0]-i))[1] for i in target]

Output
[2, 4, 5, 7]


text:
Q: Meteor JS Progresss Bar I'm working on a meteor application in which User will click on a button, then application internally makes the api call will append the result to the html. During the api call I want to show the progress bar to user, how can make it in meteor.
-thanks.

A: Adding some more information about what exactly your needs are for the progress bar may help.
In most cases, I use: https://github.com/zhouzhuojie/meteor-nprogress. You can see a demo here.
In your case, the usage would be something like:
'click #[buttonId]':function(){
   NProgress.start(); //this starts the progress bar

   Meteor.call('[method name]', function(err, res){
      if(res){
         //Do whatever you want with the result
         NProgress.end(); //this completes the progress bar
      }
   });
}


text:
Q: Do common OSes provide guarantees for IP fragment reassembly? When sending UDP packets that exceed the PMTU, I'm told that the receiver will receive the packets in fragments. Does the network interface or OS of the receiver typically re-assemble the packets automatically?
If I had to guess, for Linux/POSIX systems the answer would be no if using a raw socket e.g. SOCK_RAW - but is this also the case if using SOCK_DGRAM?
Can anyone say whether Linux, Windows, or Mac OS do IP packet reassembly?
I'm aware that the IETF recommends against IP fragmentation, but I'm trying to understand how much I, as a network application developer, have to worry about it.
How do developers using UDP deal with this issue, when using SOCK_DGRAM in particular?


text:
Q: ExecJS::RuntimeError: SyntaxError: Unexpected token: punc ()) from get@(execjs):3538:630 I have an issue when precompiling to Heroku and I checked on Stack overflow to find a debug method which is:
JS_PATH = "app/assets/javascripts/**/*.js";
Dir[JS_PATH].each do |file_name|
puts "\n#{file_name}"
puts Uglifier.compile(File.read(file_name))
end

When I run rail console with this command, it gives me an error in application.js which is
app/assets/javascripts/application.js
ExecJS::RuntimeError: SyntaxError: Unexpected token: punc ())
from get@(execjs):3538:630

The following is my application.js file which i am trying to load the page when someone make a selection from subject list or enter something in the course field. The program works perfectly when running locally but fails to deploy on Heroku. Could you please tell me where I make the run toke cuz I really cannot find it.
//= require jquery3
//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require tether
//= require popper
//= require bootstrap
$(document).on('turbolinks:load', () => {
  $('#course').on('input', function() {
    if (this.value.length > 1) Rails.fire($('.search-form')[0], 'submit')
  })
  $('#subject').on('change', () => Rails.fire($('.search-form')[0], 'submit'))
})

A: The node's version in the target machine is probably lower than your local one and does not support ES5+ js syntax.
Somewhat related to that:
SyntaxError: Unexpected token )
ES6 giving SyntaxError: Unexpected token )