text:
Q: Cable Parameters from Specs Data From a 2019 specsheet for a i.e. Belden 1583A cable, I can read \$Z_0=100 \pm15 \Omega \$ for \$f=1 \text{MHz}\$, \$\text{VF}=0.7\$, \$\text{R}=93.8 \Omega/\text{km} \$, among maximum Delay, Attenuation, and others.
If I should obtain the lumped per meter R (already given), C and L parameters for a simple transmission line model, should it be correct to take?:
$$
VF=\frac{1}{c \sqrt{LC}}, \
Z_0 = \sqrt{\frac{L}{C}} \\
C=\frac 1c\frac{1}{\text{VF}}\frac{1}{Z_0} ,\
L=Z_0\frac 1c \frac{1}{\text{VF}}
$$
Is \$VF\$ in the specsheet ("Velocity Propagation Factor") indeed the Velocity Factor I am thinking?
The specified capacitances are the Non Mutual Capacitance \$C_{NM}\$ and the Maximum Unbalance Capacitance \$C_{MU}\$.
Anyway, what are the meaning of those last capacitances?


text:
Q: Photoshop Script Resize Image Based on Pixel Dimensions (script was working now not) This script is part of a larger Photoshop action we use to process our product shots after they have been edited in Photoshop. I recently discovered this part of the action (a script) had stopped working properly.  It is supposed to take any image who's longest side is larger than 2400px and reduce it to 2400px, ignoring any image who's longest side is not larger than 2400px. But now it is running regardless of the images size which is blowing up smaller images and in the process trashing them.
We recently upgraded our Mac clients to OS 10.11 from 10.8 and during that process had to run a couple a Photoshop update as well. I would assume that one or both of these factor in. We are running Photoshop CS6 and that did not change.
#target photoshop
// get a reference to the current (active) document and store it in a  variable named "doc"
doc = app.activeDocument;

// these are our values for the end result width and height (in pixels) of our image
var fWidth = 2400;
var fHeight = 2400;

// resize. if height > width (portrait-mode) AND height is larger than 2400px -- resize based on height. otherwise, resize based on width only if width is greater than 2400px
if(doc.height > 2400,"px" || doc.width > 2400,"px") {
if (doc.height > doc.width) {
    doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
    }
else {
    doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
    }
}'

Any help with this would be appreciated.

A: Found a solution. Thanks to Mark Dee's comment (thanks Mark) on the syntax of the initial argument I decided that simplifying the syntax would be best.
The issue I ran into is that when giving PS a number it sets the units by the current unit of your ruler. So if the user's ruler is not set to the right unit, the script won't work. Here is my fix:
#target photoshop
// get a reference to the current (active) document and store it in a variable named "doc"
doc = app.activeDocument;
// setting the ruler unit to pixels
app.preferences.rulerUnits = Units.PIXELS;

// these are our values for the end result width and height (in pixels) of our image
var fWidth = 2400;
var fHeight = 2400;

// resize. if height > width (portrait-mode) AND height is larger than 2400px -- resize based on height. otherwise, resize based on width only if width is greater than 2400px
if(doc.height > 2400 || doc.width > 2400) {
if (doc.height > doc.width) {
    doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
    }
else {
    doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
    }
}
// setting the ruler unit back to inches
app.preferences.rulerUnits = Units.INCHES;

The only issue I have with it now is that it manually sets the units back to inches, I would prefer if it just put it back to "what it was previous" but I am not sure how to do that and will have to invesitgate further.

A: You can get and store the current rulerUnits setting in a variable which you can use to test against (and change to) the ruleUnits you need for your script and. After the script is finished you can use that same variable to restore the rulerUnits setting back to the way it was.
    // store current unit value
    var userPrefUnits = app.preferences.rulerUnits;

    // change to pixels if not pixels
    if(userPrefUnits !== Units.PIXELS){
       app.preferences.rulerUnits = Units.PIXELS;
    }

    // code based on pixels

    // reset preference if userPrefUnits was not pixels
    if(userPrefUnits !== Units.PIXELS){
       app.preferences.rulerUnits = userPrefUnits;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: undefined method `last_comment_at=' for # I create new post:
    def create
    params[:blog_post][:draft] = params[:draft].present?
    @post = current_user.blog_posts.new(blog_post_params)
    @post.save!
    redirect_to @post, notice: (@post.draft? ? 'Черновик сохранен' : 'Пост опубликован')
  rescue ActiveRecord::RecordInvalid
    flash[:error] = ":("
    render :new
  end

When i create new post, displaying error:
undefined method `last_comment_at=' for #<BlogPost:0x0000000adb9110>

app/models/blog_post.rb:86:in `set_last_comment_at'
app/controllers/blog_posts_controller.rb:25:in `create'
config/initializers/flash_session_cookie_middleware.rb:19:in `call'

Model BlogPost:
class BlogPost < ActiveRecord::Base
  # attr_accessible :subject, :body, :tag_list, :commentable_by, :visible_by, :attachments_attributes
  include ActiveModel::ForbiddenAttributesProtection

  belongs_to :user
  has_many :comments, as: :owner, dependent: :destroy
  has_many :attachments, as: :owner, dependent: :destroy
  has_many :photos, through: :attachments, source: :asset, source_type: 'Photo'
  has_many :videos, through: :attachments, source: :asset, source_type: 'Video'
  belongs_to :article
  has_many :blog_post_subscriptions, dependent: :destroy
  has_many :subscribers, through: :blog_post_subscriptions, class_name: 'User', source: :user
  has_one  :poll, as: :owner, dependent: :destroy
  has_many :poll_items, dependent: :destroy

  accepts_nested_attributes_for :attachments, :allow_destroy => true
  accepts_nested_attributes_for :poll, allow_destroy: true,
                                    reject_if: proc { |attributes| attributes['question'].blank? }

  validates :user, :subject, :presence => true
  validates :body, presence: true, if: :body_required?
  validates :body, length: { maximum: 65000 }
  validate :validate_duplicate, on: :create

  def body_required?
    !article.present?
  end

  # after_create :bonus_for_blog_post
  # after_create :notify_subscribers
  before_create :check_paid_attributes
  after_create :set_last_comment_at

  def notify_subscribers!
    unless draft?
      Resque.enqueue BlogPostNotifier, self.id
    end
  end

  after_save :set_published_at

  def set_published_at
    if published_at.nil? and !draft?
      update_column :published_at, Time.now
      bonus_for_blog_post!
      notify_subscribers!
    end
  end

  define_index do
    indexes subject
    indexes body
    indexes tags_line
    indexes user.username, as: :blog_post_author

    has created_at
    has published_at
    where "draft=0"
    group_by 'subject, body, tags_line, blog_posts.published_at, users.username'

    set_property delta: ThinkingSphinx::Deltas::ResqueDelta
  end

  def to_s
    subject || "[без заголовка]"
  end

  scope :drafts, where(draft: true)
  scope :public, lambda { where(draft: false).where(:published_at.lte => Time.now) }
  scope :with_privacy, lambda { |u|
    unless u.moderator?
      friend_ids = u.friend_ids + [u.id]
      public.where(' blog_posts.visible_by IS NULL OR visible_by = "all" OR ' +
            '(blog_posts.visible_by = "me" AND user_id = ?) OR' +
            '(blog_posts.visible_by = "friends" AND user_id IN (?)) OR ' +
            '(blog_posts.visible_by = "fof" AND EXISTS ' +
            '(SELECT id FROM friendships WHERE friendships.user_id = blog_posts.user_id AND ' +
            'friendships.friend_id IN (?) LIMIT 1)) OR ' +
            '(blog_posts.visible_by = "bl" AND NOT EXISTS ' +
            '(SELECT id FROM black_list_items WHERE black_list_items.owner_type="User" AND black_list_items.owner_id=blog_posts.user_id AND black_list_items.blocked_user_id=?))', u.id, friend_ids, friend_ids, u.id)
    end
  }

  def set_last_comment_at
    self.last_comment_at = created_at
    save
  end

  acts_as_taggable
  scope :tagged, lambda {|tag| tagged_with(tag) if tag }
  before_save :set_tags_line
  def set_tags_line
    self.tags_line = tag_list.join(', ')
  end

  def user_can_edit?(user)
    self.user.id == user.id or user.moderator?
  end

  def user_can_comment?(u)
    u.can_comment_blog_post? self
  end

  protected

  def bonus_for_blog_post!
    unless draft?
      user.bonus(:blog_post_bonus)
    end
  end

  def check_paid_attributes
    unless user.paid?
      self.commentable_by = self.visible_by = 'all'
    end
  end

  def validate_duplicate
    errors.add(:base, :duplicate) unless user.blog_posts.where(body: body, article_id: article_id, :created_at.gt => 1.minute.ago).empty?
  end

  private

  after_update :expire_cache

  def expire_cache
    expire_fragment "#{dom_id}_body"
    expire_fragment "#{dom_id}_body_short"
    expire_fragment "#{dom_id}_attachments"
    Rails.cache.delete "#{dom_id}_tags"
  end

  before_save :emoji

  def emoji
    self.body = Rumoji.encode self.body
  end
end

I think, problem is here:
 def set_last_comment_at
   self.last_comment_at = created_at
   save
 end

But why can't it find the method last_comment_at?

A: I fixed issue, i run migrate and added new column last_comment_at to table BlogPost


text:
Q: Updating Winform ListView control by one event handler that may be fired from several threads I have a "Win Form" application which listening to an event that may be raised from some different threads.
on that event i want to update a "List View" control.
of course that i may need to use Invoke but my question is:
 Should i use lock on the function i will build to update the "List View" control or not?
Be a ware that i am updating the List View only by one function in the form and by only one event but more than one thread may raise the same event.
is it true that all the events that may be fired from all the threads will be handled by the main thread only so they will be executed one by one?
Thanks.

A: If you think the event could be fired at the same time from multiple threads, or at least get fired again before finishing the update then yes you should lock.
Something simple like:
lock(myListView) {
  updateMyListView();
}

should be enough.  Locking on the list view object should still let you edit it.
A word of warning, this won't keep other things from editing the list view, only code that has it's own lock(myListView) block will pay attention to the lock.


text:
Q: why the application hang already use worker? I am trying to use web worker and implement it in angularjs. After implementation I realise that UI hangs; ie. the loader hangs and data is not printed.
Could you please tell me a better way so that the loader may not hang. I know you may suggest to do pagination or lazy loading or virtual display loading.
But why is it hanging now if it is working on another thread.
Here is my code
http://plnkr.co/edit/zpzIyIicY0Uwmvwxz7du?p=preview
function doSomething(){
    var str="
";
    for(var i=0;i<50000;i++){
        str+='
'+i+'
'
    }
    str+="
";

    return str;

}

self.onmessage=function(e){
    console.log("app.js")

    postMessage(doSomething())

}


text:
Q: Entity Framework Core JOIN with method syntax I have a simple db structure as follows
Order
OrderId
OrderItem
OrderItemId | OrderId | BookId | OrderItemTypeId
Book
BookId | AuthorId
I'd like to select a specific Order and all data associated with it's OrderItems plus the Author of the Book sold.
context.Orders.Include(order => order.OrderItems)
                 .ThenInclude(orderItem => orderItem.Book)
                 .ThenInclude(book => book.Author)
              .Include(order => order.OrderItems)
                 .ThenInclude(orderItem => orderItem.OrderItemType)
              .Where(order => order.Id == 1);

The bit where I get stuck is after this line
 .ThenInclude(book => book.Author)

because the lambda will now refer to a Book but I need to be back at the OrderItem level to include the OrderItemType. The only way I seem to be able to do that is to Include the OrderItems again to have that access to include the OrderItemType. It seems incorrect or at the least not very elegant. Can someone point me in the direction of a better approach using method syntax. Thank you

A: Actually your code is correct. Include restarts defining includes from the root entity, in your case context.Orders.
What you can improve here: only non-collection items including, they can be defined by full path:
context.Orders
    .Include(order => order.OrderItems)
        .ThenInclude(orderItem => orderItem.Book.Author)
    .Include(order => order.OrderItems)
        .ThenInclude(orderItem => orderItem.OrderItemType)
    .Where(order => order.Id == 1);

ThenInclude(orderItem => orderItem.Book.Author) will include Book and Author.


text:
Q: Encoding Android Camera Frames h263/h264 I want to implement a Video Chatting app on Android . I created a SurfaceView , get Camera preview and captured the frame as a byte[ ] using Camera.PreviewCallback.onPreviewFrame( ) method . Now I want to encode that byte[ ] to a h263 frame , pass over the network . Also get similar type of frame over network , decode it to a byte[ ] ( or a displayable format ) , and show it in a View . I want to do it at least 15 FPS rate . I am asking help for the encoding/decoding part .
For that purpose , which library would be suitable for me ? From where I should start ? Is my starting point wrong ? Is there any support on SDK or would I have to use NDK ? I have heard about FFMpeg/x264 library , but I could not figure out how I can use them in my purpose . It's highly appreciated If you name any library , any reference , learning path , link or code snippet . Can you help me saying any workflow I should follow ? What if I want to use h264 encoding ? I just want to get it done , GPL/LGPL license of library would not matter a lot .
I am a beginner in Android development . Any kind of assistance would be highly appreciated . Thanks in advance .

A: Use VLC's x264 for that,it would be a better option.....

A: You can try javacv, which is a wrapper for ffmpeg, and there is also an example RecordActivity to refer.


text:
Q: Lumen phpmailer: SMTP ERROR: Failed to connect to server: (0) Phpmailer Configuration: Lumen.
Previously it was working? But now the same configuration throw Failed to connect to server:
I am a newbie to laravel/lumen framework. This is my PHPmailer configuration, I don't know what I am doing wrong over here. Please somebody help me here.
<?php

namespace App\Repositories;
use App\Repositories\BaseRepository;
use App\Models\ForgetModel;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
class ForgetRepository extends BaseRepository{
private $forget;

public function __construct(ForgetModel $forget) {
    $this->forget = $forget;
}

public function save_verification_code($email,$verification_code)
{
    $query = $this->forget->onMaster()
                            ->insert(array('email'=>$email,'code'=>$verification_code));
}

public function send_forget_password_email($to,$message)
{

    $subject = 'Verification code to reset your password';
    $from = 'xyz@gmail.com';
    $body = $message;
    $headers = 'From: ' . strip_tags($from) . '\r\n';
    $headers .= 'MIME-Version: 1.0\r\n';
    $headers .= 'Content-Type: text/html; charset=ISO-8859-1\r\n';

    $mail = new PHPMailer(); // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465; // or 587
    $mail->IsHTML(true);
    $mail->Username = 'xyz@gmail.com';
    $mail->Password = '123456';
    $mail->SetFrom($from);
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->AddAddress($to);

    if(!$mail->Send()) {
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        //echo "Message has been sent";
    }
    return true;
}
}

A: 1. run the command  "composer require phpmailer/phpmailer" in your cmd.

namespace App\Repositories;
use App\Repositories\BaseRepository;
use App\Models\ForgetModel;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/phpmailer/phpmailer/src/Exception.php';
require '../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require '../vendor/phpmailer/phpmailer/src/SMTP.php';

class ForgetRepository extends BaseRepository{
private $forget;

public function __construct(ForgetModel $forget) {
    $this->forget = $forget;
}

public function save_verification_code($email,$verification_code)
{
    $query = $this->forget->onMaster()
                            ->insert(array('email'=>$email,'code'=>$verification_code));
}

public function send_forget_password_email($to,$message)
{
$mail = new PHPMailer(true);
    try {
        //Server settings
        $mail = new PHPMailer(); // create a new object
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
        $mail->SMTPOptions = array(
            'ssl' => array(
              'verify_peer' => false,
              'verify_peer_name' => false,
              'allow_self_signed' => true
            )
          );
        //$mail->Host = $host;
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 587; // or 465
        $mail->IsHTML(true);
        $mail->Username = $username;
        $mail->Password = $password;
        $mail->SetFrom($username);

        $mail->Subject = $subject;
        $mail->Body =$body;
        $mail->AddAddress($to);
        $mail->Send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    }
}
}


text:
Q: RegExp is not working properly I'm writing some function that switches urls into their embed url.
So, I have a two-dimensional array that has the original url and the embed url.
I'm trying to use RegExp to make sure this is a valid URL, but it just won't work..
This is a code that worked:
arr[x].match(/^(http:\/\/){0,1}(www.){0,1}(allmyvideos.net\/){1}([a-z0-9])+$/ig);

While this code won't work:
var sites = [
    ["allmyvideos.net/VIDID", "allmyvideos.net/embed-VIDID"]
];
var arr = document.getElementById('original').value.split("\n");
for(var x in arr)
{
    var regex = new RegExp("/^(http:\/\/){0,1}(www.){0,1}(" + sites[0][0].replace("VIDID", "").replace(/[\/]/g, "\\/") + "){1}([a-z0-9])+$/ig");
    regex.test(arr[x]);
}

What am I doing wrong here that the second approach is not working?

A: The new RegExp() constructor form doesn't use the surrounding / characters:
var re = new RegExp("thing to check", "ig");
re.test("THING to CHECK")
// => true


text:
Q: How Do You Concatenate Arrays In Actionscript 3 When Using Different Image Files? I've looked everywhere on the web to see if I could find an answer to this and I've looked throughout the Adobe Flash Builder help site too and I can't seem to find a concrete answer for what I'm trying to do.
It is possible to reference an array inside of an image file name, here's the scenario.
I have a list of images that only differ by the number at the end of the name (for example. orangeimg1.jpg, appleimg2.jpg, strawberryim3.jpg, etc. Is it possible when referencing the image that I could somehow reference the array in the file name rather than repeating the same code over and over again?
I have two different arrays set up one for fruit which has (orange, apple, stawberry) and I have another array with the numbers (1, 2, 3). I have jpg images for each of these combinations but how to I reference that in one line when I'm trying to refer to these images. I thought something like source = "[fruit].img.[number].jpg" would work but I'm a newbie so I'm pretty sure that isn't right.
Again I've found some information on the web but it doesn't refer to how it would work if I was coding a source for my images.
I'm really confused and would appreciate any help with this. Thanks.

A: Strings are concatenated using +.
var fruits:Array = ["banana", "cherry"];
var numbers:Array = [4, 2];
var source = fruits[0] + "img" + numbers[0] + ".jpg";  // bananaimg4.jpg

If you want to create multiple file names, you can use a loop:
for(var i:int = 0; i<fruits.length; i++) {
    var source = fruits[i] + "img" + numbers[i] + ".jpg";
    // ...
}

You probably don't need that numbers array. If those numbers are in order you could calculate the number in the loop:
for(var i:int = 0; i<fruits.length; i++) {
    var source = fruits[i] + "img" + (i+1) + ".jpg";
    // ...
}

A: Above answer is good but i am giving only some changes to make code more effective.
We can use for loop in given below format. it's optimized code:
var len:uint = fruits.length;
for(var i:int = 0; i<len; i++) {
        var source = fruits[i] + "img" + (i+1) + ".jpg";
        // ...
    }


text:
Q: API-Platform - Iterating Resource Via IRI In my Symfony app, I have a subscriber wherein I need to iterate over IRIs stored in an array and access their entity's methods. How can I do this?
For instance:
function sendMail ($event) {
    ...
    $instance = $event->getControllerResult();
    ...
    $recipients = $instance->getRecipients(); // returns array of IRIs
    foreach ($recipients as $recipient) {
        $r = // instance of IRI-associated entity
        if ($r instanceof User) {
            // send to user
            $email = $r->getEmail();
            // send an email
        } else if ($r instanceof Group) {
            // send to group
            foreach ($r->getUsers() as $user) {
                $email = $user->getEmail();
                // send an email
            }
        }
    }
    ...
}

Although I have likely overlooked it, I have not found a method of doing so in the documentation and my knowledge of Symfony is still growing.

A: You can try to pass IriConverterInterface $iriConverter to __constructor. And convert your Iri to an entity, like:
private $iriConverter;

public function __construct(IriConverterInterface $iriConverter)
{
    $this->iriConverter = $iriConverter;
}

public function sendMail ($event) {
   foreach ($recipients as $recipientIri) {
        $recipient = $iriConverter->getItemFromIri($recipientIri)
        if ($recipient instanceof User) {
            $email = $recipient->getEmail();
            ...
        }
    ...
    }
}


text:
Q: How check directory exist? I have functions to create directorys:
func createSystemFolders(){
        // Create a FileManager instance
        let fileManager = FileManager.default
        do {
            try fileManager.createDirectory(atPath: "json", withIntermediateDirectories: true, attributes: nil)
        }
        catch let error as NSError {
            debugPrint("\(ErrorsLabels.AppDelegate01): \(error)")
        }

        do {
            try fileManager.createDirectory(atPath: "inspirations", withIntermediateDirectories: true, attributes: nil)
        }
        catch let error as NSError {
            debugPrint("\(ErrorsLabels.AppDelegate02): \(error)")
        }

        do {
            try fileManager.createDirectory(atPath: "products", withIntermediateDirectories: true, attributes: nil)
        }
        catch let error as NSError {
            debugPrint("\(ErrorsLabels.AppDelegate03): \(error)")
        }
    }

I need second function to check directory exist.
Haw can I check it?

A: You can use this,
fileprivate func directoryExistsAtPath(_ path: String) -> Bool {
    var isdirectory : ObjCBool = true
    let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
    return exists && isDirectory.boolValue
}

A: You can do smarter solution Like that without Two function  completion(isExit,directoryURL) :
And simple use it in one line :
 self.createSystemFolders("json") { (isExit, url) in
                print(isExit)
                print(url)
            }

CreateSystemFolders:
 func createSystemFolders(_ folderName:String ,_ completion:(_ isExit:Bool?,_ directoryURL:URL?) -> Void){
    let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
    let directory = paths[0]
    let fileManager = FileManager.default

    let url = URL(fileURLWithPath: directory).appendingPathComponent(folderName)

    if !fileManager.fileExists(atPath: url.path) {
        do {
            try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
            completion(false,url)
        }
        catch {
            print("Error: Unable to create directory: \(error)")
            completion(nil,nil)
        }
        var url = URL(fileURLWithPath: directory)
        var values = URLResourceValues()
        values.isExcludedFromBackup = true
        do {
            try url.setResourceValues(values)
            completion(false,url)
        }
        catch {
            print("Error: Unable to exclude directory from backup: \(error)")
            completion(nil,nil)
        }
    }else{
        completion(true,url)
    }
}

A: Try this:
let fileManager = FileManager.default
var isdirectory = true
if fileManager.fileExists(atPath: fullPath, isDirectory:&isdirectory) {
    if isdirectory.boolValue {
        // file exists and is a directory
    } else {
        // file exists and is not a directory
    }
} else {
    // file does not exist
}

A:
here how you can

1 Find a Documents directory on device
2 Check if file exists at specified file path
let fileNameToDelete = "myFileName.txt"
        var filePath = ""
        // Fine documents directory on device
         let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)

        if dirs.count > 0 {
            let dir = dirs[0] //documents directory
            filePath = dir.appendingFormat("/" + fileNameToDelete)
            print("Local path = \(filePath)")
        } else {
            print("Could not find local directory to store file")
            return
        }

        let fileManager = FileManager.default

        // Check if file exists
        if fileManager.fileExists(atPath: filePath) {
            print("File exists")
        } else {
            print("File does not exist")
        }


text:
Q: apktool build apk fails I am experiencing very annoying problems with the application apktool problem.
I do not understand what i am doing wrong, or what the problem is.
I tried this on debian , and on linux mint. I used different versions of apktool,
resulting in the same error:
I: Checking whether sources has changed...
I: Checking whether resources has changed...
I: Building resources...
Exception in thread "main" brut.androlib.AndrolibException: brut.common.BrutException: could not exec command: [aapt, p, -F, /tmp/APKTOOL3630495287059303807.tmp, -I, /home/awesomename/apktool/framework/1.apk, -S, /home/awesomename/out/./res, -M, /home/awesomename/out/./AndroidManifest.xml]
    at brut.androlib.res.AndrolibResources.aaptPackage(Unknown Source)
    at brut.androlib.Androlib.buildResourcesFull(Unknown Source)
    at brut.androlib.Androlib.buildResources(Unknown Source)
    at brut.androlib.Androlib.build(Unknown Source)
    at brut.androlib.Androlib.build(Unknown Source)
    at brut.apktool.Main.cmdBuild(Unknown Source)
    at brut.apktool.Main.main(Unknown Source)
Caused by: brut.common.BrutException: could not exec command: [aapt, p, -F, /tmp/APKTOOL3630495287059303807.tmp, -I, /home/windows/apktool/framework/1.apk, -S, /home/windows/out/./res, -M, /home/windows/out/./AndroidManifest.xml]
    at brut.util.OS.exec(Unknown Source)
    ... 7 more
Caused by: java.io.IOException: Cannot run program "aapt": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
    at java.lang.Runtime.exec(Runtime.java:617)
    at java.lang.Runtime.exec(Runtime.java:485)
    ... 8 more
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
    at java.lang.ProcessImpl.start(ProcessImpl.java:130)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
    ... 10 more

It seems it can not use aapt , but i read about apktool.
And it seems that aapt is build inside apktool , why is it not working ?

A: In case you've been using v1 and now upgraded to v2, try manually deleting the framework file.
On windows 8 it's normally at C:\Users\YourName\apktool\framework\1.apk.
The file should be regenerated once you try to build something.

A: It seems there's some problem in building the resources while recompiling the apk.
what you can do is, when you decompile your apk use this command
apktool d -f -r apkfilename.apk

here -f is to replace previous decompiled apk's code and -r is to ignore the decompiling of resources.
this would prevent the resources from being decompiled and will simply copy the same resources when you recompile the apk.

A: My problem was solved by deleting the \framework\1.apk, making a backup on the files I modified, ereasing the dir and decompiling the *.apk again, etc...  (on linux, the path is home/[user]/apktool/...). After the update, apktool always loaded the old resource table. N

A: For me, I solved this problem by first clearing apktool's framework directory by typing in the terminal.
$ apktool empty-framework-dir

Afterwards I uninstalled apktool and related files by typing
$ sudo apt purge apktool

Then i went to https://bitbucket.org/iBotPeaches/apktool/downloads/ to get the latest jar file for apktool(apktool_2.5.0.jar as at the time of writing this).
On first run
$ java -jar apktool_2.5.0.jar b <MyAPP.apk> #Without ><

it works.
since I work with apktool most of the times I needed a situation where I can run apktool from anywhere so I gave the jar file execute permissions by typing
$ sudo chmod +x apktool_2.5.0.jar

Afterwards I moved it /usr/bin/ by typing
$ sudo apktool_2.5.0.jar /usr/bin/

A: Definitely seems like the aapt PATH problem I had awhile back. Have you added aapt to PATH? If you still have problems, I have made a good apk kit in bash to avoid all these dependency problems. It supports apktool, signapk, zipalign,adb, fastboot, and heimdall. Check it out. All you need is a current java install.
http://forum.xda-developers.com/android/development/toolkit-apk-munky-rench-t3026757/post58747626#post58747626

A: There isn't really enough information to give you a definite answer.
How ever you mentioned using different versions but the aapt issue was solved in version 2.4. Dependencies have been reduced to java version 1.8 or greater and the framework.
I use Debian and have the following:

*

*Apktool 2.4

*java version 11

*Android framework

That's all it took to get rid of the aapt path error.
The last error I came across was unrelated to aapt but was on the framework so I ran this command
apktool empty-framework-dir

And it solved it.

A: try to put the dir which include aapt file to your PATH. for example, export PATH=$PATH:./ ./apktool b

A: try to install ia32-libs and update latest version of apktool. (if possible restart)
apktool requires "ia32-libs" which is not available after Ubuntu 12.04. install ia32-libs
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6

Download latest version of apktools.jar - https://bitbucket.org/iBotPeaches/apktool/downloads
apktool complete installation guide - http://ibotpeaches.github.io/Apktool/install/

A: I just encounter same problem when run apktool d foo.apk(decompiled success) and then apktool b foo(recompile failed with similar error).
The apktool tool above was installed via sudo apt-get install apktool on Kali Linux.
So, the solution was visits apktool's official site, e.g. https://connortumbleson.com/2017/01/23/apktool-v2-2-2-released/ (it's latest version at this time of writing), download it, md5sum it, e.g. md5sum apktool_2.2.2.jar to verify, then rename that apktool_2.2.2.jar to apktool.jar.
Then do java -jar ./apktool.jar b foo to recompile, it success without error (the generated apk located at ./foo/dist/foo.apk).

A: The main issue is apktool version you need 2.4.0
You must manually install it from ibotpeaches git hub
here some good info
https://www.youtube.com/watch?v=kB6s10Uwpcs
and a automated script for kali
https://github.com/catenatedgoose?tab=repositories

A: In my mind the problem is how you install apktool...
I had the same problem and I did this and it worked very well:
For installation you first have to remove any installed apktool by the command:
sudo apt purge apktool
Then you'll have to install apktool but in a different way.
To continue save the link bellow as apktool in a directory.
[https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool]
Then open this link below and download the latest apktool.jar file: https://bitbucket.org/iBotPeaches/apktool/downloads/
Then rename the file as apktool.jar
After that give both files the permission by the command:
Sudo chmod -x apktool.jar

And for the saved script:
Sudo chmod -x apktool

At the end copy both files in the directory:
/usr/local/bin

By the command:
Sudo cp apktool.jar /usr/local/bin

And the script file:
Sudo cp apktool /usr/local/bin

After that try running apktoolin the terminal.

A: The solution is to include your apktool directory into your system PATH.


text:
Q: Backing up with Google drive I've recently switched from Windows to Linux, and have tried keeping certain things similar.  Mainly, I work in LaTeX a lot, and have stored all of my work in Google Drive.  With how Google Drive on windows works, this was at best imperfect (if while Latex was compiling a document google drive tried to sync, issues would arise), but it worked pretty well for the most part.
Now, I've switched over to a chromebook with GalliumOs, and have tried using Google Drive via OCamlfuse.  Unfortunately, this seems to make my compile times much longer (at least 10 seconds even for a simple document).  This makes this no longer an option for me, so it seems like I'll need to work locally.  Is there a way to still sync my files (even if it's only much more infrequently, or I need to trigger a sync manually) with google drive without storing the files in the directory that OCamlfuse mounts?


text:
Q: Split ArrayList on blocks I have ArrayList, that looks like this
I need to extract data based on a string which I type. For example if I type systém, I should get this output:
001 (07.01.01) programovací systém (m)
systém (m) programovaniaCHCTeMa (f) riporpaMMupoBaiiHM
programming system; programming support environmentsystème (m) de programmationProgrammiersystem (n)
nezbytné programové vybavení potrebné pro používání jed-noho nebo vice programovacích jazyku

If I type komentár, I should get:
004 (07.01.08) komentár (m); poznámka (í)
komentár (m); poznámka (f)
KOMMeHTapHH (m)
comment; remark; note; (computer program) annotationcommentaire (m)
Kommentar (m)
popis*, odkaz n. vysvetlení pripojené k príkazúmve zdrojo-vémprogramu (které se neprojevuje v cílovém programu)

But I don't know how to fix it. I've tried to recognize block through first numbers but my output was only line with this number. Here is my code:
  Pattern pattern = Pattern.compile("[0-9]+.*");
  Matcher m;

  String str = "systém";

  for (int i = 0; i < al.size(); i++) {
    String line = al.get(i).toString();
    m = pattern.matcher(line);

    if(m.matches() && line.contains(str))
      System.out.println(line);
      //...Whats next?

  }
}

A: It looks like your regex is wrong. Try
String str = "systém";
Pattern pattern = Pattern.compile(str);
Matcher m;

for (int i = 0; i < al.size(); i++) {
    String line = al.get(i).toString();
    m = pattern.matcher(line);

    if(m.matches() && line.contains(str))
        System.out.println(line);
    //...Whats next?
}


text:
Q: Tips to increase performance of the .NET client data context in WCF data services? We've been developing a new app using the following stack:
SQL Server 2008 R2 -> Entity Framework 4.2 -> WCF Data Services -> WCF Data Services Client Library
This is all .NET 4.0
Now, the WCF Data Services Client Library is very convenient for small bits of data and simple schemas/object graphs, but it's a real dog for more complex models. In particular, we've found that the DataServiceContext.Links collection scales something like O(n^2): the more related objects you load in, and the more nested your graph, the slower it gets, till it takes longer to load data into the context than it does it read it off the wire.
For example, we have a collection w/ 2000 members, and each member has 4 navigation properties. Pulling the whole collection without expanding any navigation properties takes about 1 second. Expanding all 4 navigation properties takes 5 seconds. We've measured performance at various points in the stack, and the majority of the extra time is spent on the client, collating the data.
We've adopted various techniques to work around this for large data sets:

*

*Denormalization. This works well for those graphs that we always expand. Doesn't work so well if we want to defer loading of part of the graph.

*Loading related objects separately, and stitching them together outside the data context. This is just annoying, but it does overcome the context.Links problem.

*Using multiple data contexts to keep pressure on the Links collection to a minimum.

*Using MergeOption.NoTracking in connection w/ (1) & (2)

Does anyone know any other techniques? Is there a setting someplace that might be causing unnecessary overhead when loading related objects?
At times it seems like we are half-way to writing our own custom context, and I'd like a sanity check before it gets any more elaborate.
[Yes, I realize that WCF Data Services may be the wrong tool for the job. Alas, we are already down that road]


text:
Q: Why the album photos coming null from Facebook Graph request in iOS? I am trying to write a code in iOS to fetch list of Facebook photos from a specific album but from my iOS app , i am not able to retrieve the list of photos from a album id. It return null.
MyCode:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                              initWithGraphPath:@"/195146297190415/picture"
                              parameters:@{@"fields": @"url"}
                              HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
    NSLog(@"fetched Albums Photo:%@", result);

}];

So , this is the above iOS code retreive photos from a album id. Please let me know , where i am doing wrong and why list of photos are coming null.


text:
Q: Multithread SQL select statements I am a multithreading novice and a SQL novice, so please excuse any rookie mistakes.
I am trying to execute many SQL queries asynchronously. The queries are all select statements from the same table in the same database. I can run them synchronously and everything works fine, but testing a small subset leads me to believe that to run all the queries synchronously would take approximately 150 hours, which is far too long. As such, I'm trying to figure out how to run them in parallel.
I have tried to model the code after the answer at run a method multiple times simultaneously in c#, but my code is not executing correctly (it's erroring, though I do not know specifically how. The code just says an error occurs).
Here is what I have (A much smaller and simpler version of what I am actually doing):
class Program
{
    static void Main(string[] args)
    {
        List<string> EmployeeIDs = File.ReadAllLines(/* Filepath */);
        List<Tuple<string, string>> NamesByID = new List<Tuple<string, string>>();

        //What I do not want to do (because it takes too long) ...
        using (SqlConnection conn = new SqlConnection(/* connection string */))
        {
            foreach (string id in EmployeeIDs)
            {
                using (SqlCommand cmd = new SqlCommand("SELECT FirstName FROM Employees WITH (NOLOCK) WHERE EmployeeID = " + id, conn))
                {
                    try
                    {
                        conn.Open();
                        NamesByID.Add(new Tuple<string, string> (id, cmd.ExecuteScalar().ToString()));
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }

        //What I do want to do (but it errors) ...
        var tasks = EmployeeIDs.Select(id => Task<Tuple<string, string>>.Factory.StartNew(() => RunQuery(id))).ToArray();
        Task.WaitAll(tasks);
        NamesByID = tasks.Select(task => task.Result).ToList();
    }

    private static Tuple<string, string> RunQuery(string id)
    {
        using (SqlConnection conn = new SqlConnection(/* connection string */))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT FirstName FROM Employees WITH (NOLOCK) WHERE EmployeeID = " + id, conn))
            {
                try
                {
                    conn.Open();
                    return new Tuple<string, string> (id, cmd.ExecuteScalar().ToString());
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
}

Note: I do not care exactly how this is multithreaded (tasks, parallel.foreach, backgroundworker, etc). This is going to be used to run ~30,000 select queries exactly 1 time, so I just need it to run fast (I'm hoping for ~8 hrs = one work day, but I'll take what I can get) one time. It doesn't have to really be pretty.
Thank you in advance!

A: This is just plain wrong. You should build one query to select all FirstNames you need. If you need to pass a bunch of ids to the server, that is no problem, just use table valued parameter (aka TVP), coma separated list of values really does not scale well. If the query is correctly written and the tables indexed, that should be quite fast. 100k rows table is a small table.
The query then may look like this
SELECT DollarAmount, comp.CompanyID
FROM Transactions
JOIN (SELECT MIN(TransactionID) as minTransactionID, CompanyID
      FROM CompanyTransactions
      GROUP BY CompanyID
     ) AS comp
ON Transactions.TransactionID = comp.minTransactionID
JOIN @IDList ON id = comp.CompanyID

You may use IN instead of JOIN if the ids in TVP are not unique.
Btw. do you know what NOLOCK means? If you are the only user of the database and use it single threaded or do not modify any data, then you are safe. Other than that it means that you are okay with a small chance of:

*

*some records may be missing in the result

*there are duplicate records in the result

*there are rows in the result, that have never been committed and never were accepted as valid data

*if you use varchar(max), you may get text that has never been stored

A: You want to do one query to get all of the ID/Name combinations, then put them into a dictionary (for quick access).  This will remove the very slow process of running 30,000 queries as well as reduce the complexity of your code.
I could get you something more concrete if you posted the actual SQL query (you can change the column and table names if you need) but this should be close:
;WITH CompTransCTE AS (
    SELECT CompanyID, MIN(TransactionID) AS TransactionID
    FROM CompanyTransactions
    WHERE CompanyID IN (/*Comma seperated list of values*/)
    GROUP BY CompanyID
)
SELECT CT.CompanyID, T.DollarAmount, T.TransactionID
FROM Transactions AS T
INNER JOIN CompTransCTE AS CT ON CT.TransactionID = T.TransactionID;

A: Without creating a User-Defined Table Type in the database, you can use SqlBulkCopy to load the IDs into a temp table, and reference that in the query.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace ConsoleApp11
{
    class Program
    {

        static void Main(string[] args)
        {
            //var EmployeeIDs = File.ReadAllLines(""/* Filepath */);
            var EmployeeIDs = Enumerable.Range(1, 30 * 1000).ToList();
            var dt = new DataTable();
            dt.Columns.Add("id", typeof(int));

            dt.BeginLoadData();
            foreach (var id in EmployeeIDs)
            {
                var row = dt.NewRow();
                row[0] = id;
                dt.Rows.Add(row);
            }
            dt.EndLoadData();

            using (SqlConnection conn = new SqlConnection("server=.;database=tempdb;integrated security=true"))
            {
                conn.Open();

                var cmdCreateTemptable = new SqlCommand("create table #ids(id int primary key)",conn);
                cmdCreateTemptable.ExecuteNonQuery();

                //var cmdCreateEmpable = new SqlCommand("create table Employees(EmployeeId int primary key, FirstName varchar(2000))", conn);
                //cmdCreateEmpable.ExecuteNonQuery();

                var bc = new SqlBulkCopy(conn);
                bc.DestinationTableName = "#ids";
                bc.ColumnMappings.Add("id", "id");
                bc.WriteToServer(dt);

                var names = new List<string>();
                var cmd = new SqlCommand("SELECT FirstName, EmployeeId FROM Employees WHERE EmployeeID in (select id from #ids)", conn);
                using (var rdr = cmd.ExecuteReader())
                {
                    var firstName = rdr.GetString(0);
                    var id = rdr.GetInt32(1);
                    names.Add(firstName);
                }

                Console.WriteLine("Hit any key to continue");
                Console.ReadKey();
            }

        }

    }
}


text:
Q: How to make circular progress bar in kivy? I thought to make one simple circular progress bar using kivy and python. I searched online documentation and GitHub repertoires, but not found single proper example explaining the concept of circular progress bar .
Like the image attached below. I thought to develop. Please anyone help me in this issue.

A: New, better version
This post has received much more attention than I expected, therefore I've decided to put a little bit of effort into creating an upgraded version of this widget. It is now available on GitHub. Here is a sample of what can be done with it (the progress bars are actually transparent, I have added a black background to the gif to make everything visible):

I will keep the old post for reference below, if anyone is interested.
Old post
I've made a widget to represent what you want to achieve. There are some limitations however, precisely:

*

*Instead of just setting the progress bar value using .value, you need to call the set_value method. I am very unsure what should be done to achieve the same behaviour as in original ProgressBar class;

*You have to specify the size to achieve a circle, because the object itself is an ellipse.
Here is the code, also with example usage:
from kivy.app import App
from kivy.uix.progressbar import ProgressBar
from kivy.core.text import Label as CoreLabel
from kivy.lang.builder import Builder
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.clock import Clock

class CircularProgressBar(ProgressBar):

    def __init__(self, **kwargs):
        super(CircularProgressBar, self).__init__(**kwargs)

        # Set constant for the bar thickness
        self.thickness = 40

        # Create a direct text representation
        self.label = CoreLabel(text="0%", font_size=self.thickness)

        # Initialise the texture_size variable
        self.texture_size = None

        # Refresh the text
        self.refresh_text()

        # Redraw on innit
        self.draw()

    def draw(self):

        with self.canvas:

            # Empty canvas instructions
            self.canvas.clear()

            # Draw no-progress circle
            Color(0.26, 0.26, 0.26)
            Ellipse(pos=self.pos, size=self.size)

            # Draw progress circle, small hack if there is no progress (angle_end = 0 results in full progress)
            Color(1, 0, 0)
            Ellipse(pos=self.pos, size=self.size,
                    angle_end=(0.001 if self.value_normalized == 0 else self.value_normalized*360))

            # Draw the inner circle (colour should be equal to the background)
            Color(0, 0, 0)
            Ellipse(pos=(self.pos[0] + self.thickness / 2, self.pos[1] + self.thickness / 2),
                    size=(self.size[0] - self.thickness, self.size[1] - self.thickness))

            # Center and draw the progress text
            Color(1, 1, 1, 1)
            #added pos[0]and pos[1] for centralizing label text whenever pos_hint is set
            Rectangle(texture=self.label.texture, size=self.texture_size,
                  pos=(self.size[0] / 2 - self.texture_size[0] / 2 + self.pos[0], self.size[1] / 2 - self.texture_size[1] / 2 + self.pos[1]))

    def refresh_text(self):
        # Render the label
        self.label.refresh()

        # Set the texture size each refresh
        self.texture_size = list(self.label.texture.size)

    def set_value(self, value):
        # Update the progress bar value
        self.value = value

        # Update textual value and refresh the texture
        self.label.text = str(int(self.value_normalized*100)) + "%"
        self.refresh_text()

        # Draw all the elements
        self.draw()

class Main(App):

    # Simple animation to show the circular progress bar in action
    def animate(self, dt):
        if self.root.value < 80:
            self.root.set_value(self.root.value + 1)
        else:
            self.root.set_value(0)

    # Simple layout for easy example
    def build(self):
        container = Builder.load_string(
            '''CircularProgressBar:
    size_hint: (None, None)
    height: 200
    width: 200
    max: 80''')

        # Animate the progress bar
        Clock.schedule_interval(self.animate, 0.1)
        return container

if __name__ == '__main__':
    Main().run()

Output:


text:
Q: How to make background black of react native camera? Problem:
I have created react native camera but it is looked like this.

But the problem is the background color of camera action icons are transparent.
This is my code.
import React, {useState, useEffect} from 'react';
import {
  AppRegistry,
  StyleSheet,
  TouchableOpacity,
  View,
  Image,
  CameraRoll,
  Platform,
} from 'react-native';
import IoniconsIcon from 'react-native-vector-icons/Ionicons';
import EntypoIcon from 'react-native-vector-icons/Entypo';
import AppText from '_components/appText';
import {RNCamera} from 'react-native-camera';
import normalize from '_utils/fontsize';
let countRecordTime;

const PendingView = () => (
  <View
    style={{
      flex: 1,
      backgroundColor: 'lightgreen',
      justifyContent: 'center',
      alignItems: 'center',
    }}>
    <AppText>Waiting</AppText>
  </View>
);

const takePicture = async (camera) => {
  const options = {quality: 1};
  const data = await camera.takePictureAsync(options);
  console.log(data.uri);
};

const recordVideo = async (
  camera,
  recording,
  seconds,
  setRecording,
  setSeconds,
) => {
  if (camera) {
    if (!recording) {
      startRecording(recording, setRecording, seconds, setSeconds, camera);
    } else {
      stopRecording(camera, setSeconds);
    }
  }
};

const startRecording = async (
  recording,
  setRecording,
  seconds,
  setSeconds,
  camera,
) => {
  setRecording(true);
  console.log('>>>>>> start recording seconds', seconds);
  const cameraConfig = {maxDuration: 20};
  const data = await camera.recordAsync(cameraConfig);
  console.log('>>>>>> data', data);
  setRecording(false);
};

const stopRecording = (camera, setSeconds) => {
  camera.stopRecording();
  setSeconds(0);
};

const secondsToMMSS = (seconds) => {
  console.log('>>>>>> seconds', seconds);
  let m = Math.floor(seconds / 60);
  let s = Math.floor(seconds % 60);

  let mDisplay = m < 10 ? `0${m}` : `${m}`;
  let sDisplay = s < 10 ? `0${s}` : `${s}`;
  return `${mDisplay}:${sDisplay}`;
};

const VideoRecording = (props) => {
  const [type, setType] = useState(RNCamera.Constants.Type.back);
  const [flashMode, setFlashMode] = useState(RNCamera.Constants.FlashMode.off);
  const [recording, setRecording] = useState(false);
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    if (recording) {
      countRecordTime = setInterval(() => setSeconds(seconds + 1), 1000);
    }
    if (!recording && countRecordTime) {
      clearInterval(countRecordTime);
    }

    if (seconds === 20 && countRecordTime) {
      clearInterval(countRecordTime);
      setRecording(false);
    }

    return () => {
      if (countRecordTime) {
        clearInterval(countRecordTime);
      }
    };
  }, [recording, seconds]);

  return (
    <View style={styles.container}>
      <RNCamera
        style={styles.preview}
        autoFocus={RNCamera.Constants.AutoFocus.on}
        type={type}
        flashMode={flashMode}
        faceDetectionMode={RNCamera.Constants.FaceDetection.Mode.fast}
        ratio="4:3"
        whiteBalance={RNCamera.Constants.WhiteBalance.auto}
        captureAudio={true}
        androidCameraPermissionOptions={{
          title: 'Permission to use camera',
          message: 'We need your permission to use your camera',
          buttonPositive: 'Ok',
          buttonNegative: 'Cancel',
        }}
        androidRecordAudioPermissionOptions={{
          title: 'Permission to use audio recording',
          message: 'We need your permission to use your audio',
          buttonPositive: 'Ok',
          buttonNegative: 'Cancel',
        }}>
        {({camera, status, recordAudioPermissionStatus}) => {
          if (status !== 'READY') {
            return <PendingView />;
          }
          return (
            <>
              <View
                style={{
                  flex: 0,
                  flexDirection: 'row',
                  justifyContent: 'center',
                }}>
                <TouchableOpacity
                  style={styles.capture}
                  onPress={(_) => {
                    switch (flashMode) {
                      case RNCamera.Constants.FlashMode.off:
                        setFlashMode(RNCamera.Constants.FlashMode.auto);
                        break;

                      case RNCamera.Constants.FlashMode.auto:
                        setFlashMode(RNCamera.Constants.FlashMode.on);
                        break;

                      case RNCamera.Constants.FlashMode.on:
                        setFlashMode(RNCamera.Constants.FlashMode.off);
                        break;
                    }
                  }}>
                  <Image
                    source={
                      flashMode === RNCamera.Constants.FlashMode.auto
                        ? require('../../assets/img/flashAuto.png')
                        : flashMode === RNCamera.Constants.FlashMode.on
                        ? require('../../assets/img/flashOn.png')
                        : require('../../assets/img/flashOff.png')
                    }
                    style={{width: 30, height: 30}}
                    resizeMode={'contain'}
                  />
                </TouchableOpacity>
                {/* <TouchableOpacity
                  onPress={() => takePicture(camera)}
                  style={styles.capture}>
                  <Image
                    source={require('../../assets/img/cameraButton.png')}
                    style={{width: 50, height: 50}}
                    resizeMode={'contain'}
                  />
                </TouchableOpacity> */}
                <TouchableOpacity
                  style={styles.iconContainer}
                  onPress={() =>
                    recordVideo(
                      camera,
                      recording,
                      seconds,
                      setRecording,
                      setSeconds,
                    )
                  }>
                  <EntypoIcon
                    style={styles.icon}
                    size={40}
                    color={recording ? 'red' : 'white'}
                    name="video-camera"
                  />
                  {recording ? (
                    <AppText styles={styles.recordingTime}>
                      {secondsToMMSS(seconds)}
                    </AppText>
                  ) : null}
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.capture}
                  onPress={(_) => {
                    if (type === RNCamera.Constants.Type.back) {
                      setType(RNCamera.Constants.Type.front);
                    } else {
                      setType(RNCamera.Constants.Type.back);
                    }
                  }}>
                  <Image
                    source={require('../../assets/img/cameraFlipIcon.png')}
                    style={{width: 40, height: 40}}
                    resizeMode={'contain'}
                  />
                </TouchableOpacity>
              </View>
              <TouchableOpacity style={styles.closeButton} onPress={() => {}}>
                <IoniconsIcon
                  name={'ios-close'}
                  style={styles.closeButtonIcon}
                />
              </TouchableOpacity>
            </>
          );
        }}
      </RNCamera>
    </View>
  );
};

export default VideoRecording;

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
    backgroundColor: 'black',
  },
  capture: {
    flex: 0,
    borderRadius: 5,
    padding: 15,
    paddingHorizontal: 20,
    alignSelf: 'center',
    margin: 20,
  },
  cptureView: {
    backgroundColor: '#ffffff',
    width: 100,
    height: 100,
    borderRadius: 100,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: '20%',
    marginTop: '5%',
  },
  camIcon: {
    color: '#858181',
  },
  iconContainer: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    marginHorizontal: 15,
    // paddingVertical: 10,
  },
  recordingTime: {
    color: 'red',
  },
  closeButton: {
    position: 'absolute',
    backgroundColor: '#aaaaaab0',
    width: 50,
    height: 50,
    borderRadius: 25,
    justifyContent: 'center',
    top: Platform.OS === 'ios' ? 45 : 10,
    left: 10,
  },
  closeButtonIcon: {
    fontSize: Platform.OS === 'ios' ? 40 : 40,
    fontWeight: 'bold',
    alignSelf: 'center',
    lineHeight: Platform.OS === 'ios' ? 58 : 40,
  },
});

Can someone help me to make it black? I tried a lot to find out way to do so that. But I could not so if someone can help me it would be grateful. Thank you very much.

A: Have you try this?
...
<View
style={{
  flex: 0,
  flexDirection: 'row',
  justifyContent: 'center',
  backgroundColor: "#000000", //-----------------Here?
}}>
<TouchableOpacity
  style={styles.capture}
  onPress={(_) => {
    switch (flashMode) {
      case RNCamera.Constants.FlashMode.off:
        setFlashMode(RNCamera.Constants.FlashMode.auto);
...


text:
Q: How to get the Refresh Token with the django-graphql-social-auth library Hi I am using the django-graphql-social-auth library and whenever I create a social user using this mutation:
import graphene
import graphql_social_auth

class Mutations(graphene.ObjectType):
    social_auth = graphql_social_auth.SocialAuthJWT.Field()

and this Graphql mutation:
mutation SocialAuth($provider: String!, $accessToken: String!) {
  socialAuth(provider: $provider, accessToken: $accessToken) {
    social {
      uid
    }
    token
    refreshToken
    }
 }

I get this error:
    {
  "errors": [
    {
      "message": "Cannot query field \"refreshToken\" on type \"SocialAuthJWT\".",
      "locations": [
        {
          "line": 29,
          "column": 5
        }
      ]
    }
  ]
}

Thanks in advance for your help.

A: I solved it as follows:
    # Social authentication
class SocialAuth(graphql_social_auth.SocialAuthMutation):
    token = graphene.String()
    refresh_token = graphene.String()

    @classmethod
    def resolve(cls, root, info, social, **kwargs):
        if social.user.refresh_tokens.count() >= 1:
            return cls(token=get_token(social.user), refresh_token=social.user.refresh_tokens.last())
        else:
            return cls(token=get_token(social.user), refresh_token=create_refresh_token(social.user))


text:
Q: How to iterate through column names and and do the same procedure on each column in Pandas I currently have two large dataframes which I will condense for the purpose of this questions.  Dataframe 1 has a list of probesets and transcripts.  I must match the transcripts to the corresponding transcripts in dataframe 2 and get the data for each subjet as you can see below:
       Probeset       Transcript
0    1554784_at  ENST00000547702
1           NaN  ENST00000547849
2     212983_at  ENST00000311189
3           NaN  ENST00000397596
4  1566643_a_at  ENST00000587894

and then the following dataframe where I need to match the transcripts:
     transcript_id  phchp230v2  phchp273v3  phchp367v3  phchp201v2
0  ENST00000547702    0.000000    0.000000    0.000000    0.000000
1  ENST00000547849    0.000000    0.000000    0.000000    0.000000
2  ENST00000311189    0.336418    0.044721    0.155847    1.676620
3  ENST00000397596    0.027106    0.016806    0.014509    0.022015
4  ENST00000587894    0.048200    0.089618    0.046528    0.000000

What I need to do is match the transcripts that are in dataframe 1 with the transcripts in dataframe 2 and get the data that is in each transcript for that specific subject that is at the top of dataframe 2. However, there is a lot of data in each of these so I would have to search for the transcripts and the corresponding data for that transcript as they are in just in order how I showcased.  The expected output is as shows:
       Probeset       Transcript  phchp230v2  phchp273v3  phchp367v3  phchp201v2
0    1554784_at  ENST00000547702    0.000000    0.000000    0.000000    0.000000
1           NaN  ENST00000547849    0.000000    0.000000    0.000000    0.000000
2     212983_at  ENST00000311189    0.336418    0.044721    0.155847    1.676620
3           NaN  ENST00000397596    0.027106    0.016806    0.014509    0.022015
4  1566643_a_at  ENST00000587894    0.048200    0.089618    0.046528    0.000000

I'm not sure how to go about finding the transcripts and then placing the specific data found with the correct subject headers as well, thank you all in advance!

A: You can merge them by .merge(), as follows:
(Assuming the first/second dataframes are called df1/df2 respectively)
df_out = df1.merge(df2.rename({'transcript_id': 'Transcript'}, axis=1), on='Transcript', how='left')

Result:
print(df_out)

       Probeset       Transcript  phchp230v2  phchp273v3  phchp367v3  phchp201v2
0    1554784_at  ENST00000547702    0.000000    0.000000    0.000000    0.000000
1           NaN  ENST00000547849    0.000000    0.000000    0.000000    0.000000
2     212983_at  ENST00000311189    0.336418    0.044721    0.155847    1.676620
3           NaN  ENST00000397596    0.027106    0.016806    0.014509    0.022015
4  1566643_a_at  ENST00000587894    0.048200    0.089618    0.046528    0.000000


text:
Q: android ANR file not showing thread/stack info I met an anr using my application. When I dump the anr file from /data/anr directory, the content is like below:

It is really confusing why this happens. How can I investigate it?


text:
Q: To find the eigen-vectors for an infinitely differentiable function Let
$$V = \{f : \Bbb{R} \to  \Bbb{R} | f \text{ infinitely many times differentiable functions} \}$$ be the vector space over $\Bbb{R}$. Find the eigenvectors of the differential operator $d/dt : V \to V$ . I had taken $f = e^{λt}$, and so $e^{λt}$ is the eigen vectors for every λ in  $\Bbb{R}$.  Is this the correct approach? Is there any matrix representation for this operator?


text:
Q: powershell command to disable combination keys in windows registry Is there any commands to disable below combination keys without reboot of system to use in java swing application(in jframe full screen) :
1.Alt and tab pressed at same time.
2.Disable notification from 3rd party application like outlook mail etc.
3.Disable Alt+space showing certain tabs.
Note:need commands that suit windows 7,8,10 versions


text:
Q: why some tcp packets doesn't have sequence number in tcpdump? I have a redis server on my host(macOS), it's port is 6378, first I execute this command:
sudo tcpdump -vvvn -i lo0 port 6378

Then execute this in another tab
redis-cli -h 127.0.0.1 -p 6378

And here is the results from tcpdump after redis-cli connected to redis-server
21:29:05.866610 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 64, bad cksum 0 (->3cb6)!)
    127.0.0.1.64020 > 127.0.0.1.6378: Flags [S], cksum 0xfe34 (incorrect -> 0xf8d2), seq 1870296365, win 65535, options [mss 16344,nop,wscale 6,nop,nop,TS val 3029686726 ecr 0,sackOK,eol], length 0
21:29:05.866682 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 64, bad cksum 0 (->3cb6)!)
    127.0.0.1.6378 > 127.0.0.1.64020: Flags [S.], cksum 0xfe34 (incorrect -> 0x4dad), seq 3099403233, ack 1870296366, win 65535, options [mss 16344,nop,wscale 6,nop,nop,TS val 962237723 ecr 3029686726,sackOK,eol], length 0
21:29:05.866693 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 52, bad cksum 0 (->3cc2)!)
    127.0.0.1.64020 > 127.0.0.1.6378: Flags [.], cksum 0xfe28 (incorrect -> 0xaeb6), seq 1, ack 1, win 6379, options [nop,nop,TS val 3029686726 ecr 962237723], length 0
21:29:05.866701 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 52, bad cksum 0 (->3cc2)!)
    127.0.0.1.6378 > 127.0.0.1.64020: Flags [.], cksum 0xfe28 (incorrect -> 0xaeb6), seq 1, ack 1, win 6379, options [nop,nop,TS val 962237723 ecr 3029686726], length 0
21:29:05.866949 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 69, bad cksum 0 (->3cb1)!)
    127.0.0.1.64020 > 127.0.0.1.6378: Flags [P.], cksum 0xfe39 (incorrect -> 0x2629), seq 1:18, ack 1, win 6379, options [nop,nop,TS val 3029686726 ecr 962237723], length 17
21:29:05.866967 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 52, bad cksum 0 (->3cc2)!)
    127.0.0.1.6378 > 127.0.0.1.64020: Flags [.], cksum 0xfe28 (incorrect -> 0xaea5), seq 1, ack 18, win 6379, options [nop,nop,TS val 962237723 ecr 3029686726], length 0
21:29:05.907727 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 86, bad cksum 0 (->3ca0)!)
    127.0.0.1.6378 > 127.0.0.1.64020: Flags [P.], cksum 0xfe4a (incorrect -> 0xde76), seq 1:35, ack 18, win 6379, options [nop,nop,TS val 962237762 ecr 3029686726], length 34
21:29:05.907757 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 52, bad cksum 0 (->3cc2)!)
    127.0.0.1.64020 > 127.0.0.1.6378: Flags [.], cksum 0xfe28 (incorrect -> 0xae35), seq 18, ack 35, win 6379, options [nop,nop,TS val 3029686765 ecr 962237762], length 0

But in wireshark, it has a sequence number

And from here we can know that every packet of TCP must have a 32bit "Sequence Number", so, should I add some args to tcpdump so it can show the seq number of lines that has Flags [.]?

A: According to the Transmission_Control_Protocol on Wikipedia:

Sequence number (32 bits)
Has a dual role:
If the SYN flag is set (1), then this is the initial sequence number. The sequence number of the actual first data byte and the acknowledged number in the corresponding ACK are then this sequence number plus 1.
If the SYN flag is clear (0), then this is the accumulated sequence number of the first data byte of this segment for the current session.

And according to the Stevens's TCP IP Illustrated, Volume 1:

Every TCP segment (except those exchanged during connection establishment)
includes a valid Sequence Number field, an ACK Number or Acknowledgment field, and a Window Size field (containing the window advertisement).

Now let's construct a scenario and use tcpdump to trace the tcp segments:

*

*Initialize a HTTP (i.e. TCP) request with curl:

$ curl -iIL https://blog.codefarm.me/
HTTP/2 200
server: GitHub.com
.....

*Meanwhile, executing tcpdump and write the dump date to a file as below:

tcpdump -n port 443 -r /tmp/https.pcap

*Reading the dump data with the following command:

$ tcpdump --number -ntS port 443 -r /tmp/https.pcap
reading from file /tmp/https.pcap, link-type EN10MB (Ethernet), snapshot length 262144
    1  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [S], seq 2427498844, win 64240, options [mss 1460,sackOK,TS val 2733586448 ecr 0,nop,wscale 7], length 0
    2  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [S.], seq 1574645920, ack 2427498845, win 64240, options [mss 1460], length 0
    3  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [.], ack 1574645921, win 64240, length 0
    4  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427498845:2427499362, ack 1574645921, win 64240, length 517
    5  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499362, win 64240, length 0
    6  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [P.], seq 1574645921:1574650508, ack 2427499362, win 64240, length 4587
    7  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [.], ack 1574650508, win 61320, length 0
    8  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427499362:2427499442, ack 1574650508, win 62780, length 80
    9  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427499442:2427499488, ack 1574650508, win 62780, length 46
   10  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427499488:2427499537, ack 1574650508, win 62780, length 49
   11  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499442, win 64240, length 0
   12  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499488, win 64240, length 0
   13  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499537, win 64240, length 0
   14  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427499537:2427499640, ack 1574650508, win 62780, length 103
   15  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499640, win 64240, length 0
   16  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [P.], seq 1574650508:1574651050, ack 2427499640, win 64240, length 542
   17  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [P.], seq 1574651050:1574651109, ack 2427499640, win 64240, length 59
   18  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [.], ack 1574651109, win 62780, length 0
   19  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427499640:2427499671, ack 1574651109, win 62780, length 31
   20  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499671, win 64240, length 0
   21  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [P.], seq 1574651109:1574651502, ack 2427499671, win 64240, length 393
   22  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [P.], seq 2427499671:2427499695, ack 1574651502, win 62780, length 24
   23  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499695, win 64240, length 0
   24  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [F.], seq 2427499695, ack 1574651502, win 62780, length 0
   25  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499696, win 64239, length 0
   26  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [FP.], seq 1574651502:1574651526, ack 2427499696, win 64239, length 24
   27  IP 192.168.91.128.32868 > 185.199.108.153.443: Flags [R], seq 2427499696, win 0, length 0

The packets at the line 11-13 are all ACK segments without palyload. And tcpdump also doesn't show the seq field which is should be 1574650508 as the last sending segment with payload from server (i.e. packet 6 at line number 6).
Why?
Now let's run tcpdump with the following options:
$ tcpdump --number -ntSxx port 443 -r /tmp/https.pcap
.....
    6  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [P.], seq 1574645921:1574650508, ack 2427499362, win 64240, length 4587
.....
   11  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499442, win 64240, length 0
    0x0000:  000c 298c df3f 0050 56e9 f627 0800 4500
    0x0010:  0028 5a0e 0000 8006 9e38 b9c7 6c99 c0a8
    0x0020:  5b80 01bb 8064 5ddb 428c 90b0 b3b2 5010
    0x0030:  faf0 0b70 0000 0000 0000 0000
   12  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499488, win 64240, length 0
    0x0000:  000c 298c df3f 0050 56e9 f627 0800 4500
    0x0010:  0028 5a0f 0000 8006 9e37 b9c7 6c99 c0a8
    0x0020:  5b80 01bb 8064 5ddb 428c 90b0 b3e0 5010
    0x0030:  faf0 0b42 0000 0000 0000 0000
   13  IP 185.199.108.153.443 > 192.168.91.128.32868: Flags [.], ack 2427499537, win 64240, length 0
    0x0000:  000c 298c df3f 0050 56e9 f627 0800 4500
    0x0010:  0028 5a10 0000 8006 9e36 b9c7 6c99 c0a8
    0x0020:  5b80 01bb 8064 5ddb 428c 90b0 b411 5010
    0x0030:  faf0 0b11 0000 0000 0000 0000
.....

Actually, with the xx option, we can analyze the 32bit sequence number (i.e. 5ddb 428c) of the above TCP segments (11-13) and convert it to decimal number as below:
$ echo $((16#5ddb428c))
1574650508

Here, we can see the sequence number that repeated in ACK segment three times is 1574650508 which is same as the WireShark (with absolute sequence number option).


text:
Q: How to use ParamGridBuilder for ASL 0.9.0 on pyspark 3.2.0 I'm using ASL 0.9.0 on pyspark 3.2.0. When I set up the model, it only allowed me to set up as a blank model
asl = ALS()

If I input any param I would get error:
als = ALS(rank=5)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-7f1df7a9fa59> in <module>
----> 1 als = ALS(rank=5)

TypeError: ALS() takes no arguments

When I trained the model with fixed parameter it worked fine.
model = als.train(train_rdd, rank=5, iterations=5, lambda_=0.01, blocks=- 1, nonnegative=False, seed=None)

However, when I tried to use ParamGridBuilder, I kept getting message 'ALS' object has no attribute for all the parameters.
My code:
param_grid = ParamGridBuilder() \
            .addGrid(als.rank, [10, 50, 100, 150]) \
            .addGrid(als.iterations, [20]) \
            .addGrid(als.regParam, [.01, .05, .1, .15]) \
            .build()

I am getting this error:
AttributeError                            Traceback (most recent call last)
<ipython-input-14-0e6e7cbffc91> in <module>
----> 1 param_grid = ParamGridBuilder().addGrid(als.rank, [10, 50, 100, 150]).addGrid(als.iterations, [20]).addGrid(als.regParam, [.01, .05, .1, .15]).build()

AttributeError: 'ALS' object has no attribute 'rank'


text:
Q: receive a video file with a microcontroller I want to send a video stream to a microcontroller via wifi. what microcontroller choose for this task?
-Must take into account that the video will be transmitted through a phone
-The video will be in different format and larger format will be HD (1920 * 1080)
-The video is intended to be displayed on a TV screen
-The video will be played at the same time it is to be sent to crotch...
I work on a project to read streaming a video that is in the phone by a plasma tv...
 I had my start and I still looking for landmarks

A: Microcontrollers, are designed for simple tasks, they can not do any thing any where near video, what you need is a microprocessor, that is capable of processing video.


text:
Q: How to fix labels in chart.js I am using chart.js for the first time for my project and when I passed my labels into the chart.js component, instead of taking strings like "sunday" and "monday" as labels, it takes "s" , "u", "n" ,"d" etc. How to fix this issue:

Code for the bar chart:
<template>
  <canvas :id="`myChart${id}`"></canvas>
</template>

<script>
import Chart from 'chart.js/auto';
export default {
  name: 'AnalysisBarChart',
  props: ['id', 'labels'],
  mounted() {
    const ctx = document.getElementById('myChart' + this.id).getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: this.labels,
        datasets: [
          {
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
              'rgba(255, 99, 132, 0.2)',
              'rgba(54, 162, 235, 0.2)',
              'rgba(255, 206, 86, 0.2)',
              'rgba(75, 192, 192, 0.2)',
              'rgba(153, 102, 255, 0.2)',
              'rgba(255, 159, 64, 0.2)',
            ],
            borderColor: [
              'rgba(255, 99, 132, 1)',
              'rgba(54, 162, 235, 1)',
              'rgba(255, 206, 86, 1)',
              'rgba(75, 192, 192, 1)',
              'rgba(153, 102, 255, 1)',
              'rgba(255, 159, 64, 1)',
            ],
            borderWidth: this.id,
          },
        ],
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      },
    });
    myChart;
  },
};
</script>

<style></style>

And I pass these labels:
labels: ['sunday', 'monday'],

How to fix this issue?

A: This behaviour only appears when you provide your labels array as a string instead of an array. So your labels array is not an array as you say it is but instead it is a string that looks like an array.
So you will need to convert that strong back to an array and then it will work as expected


text:
Q: How to create a variable in build time? I have this page:
<c:forEach begin="0" end="#{tareaController.tipoFuncion.filas}" step="1" var="x">
    <p:row>
        <c:forEach begin="0" end="#{tareaController.tipoFuncion.columnas}" step="1" var="y">
            <c:choose>
                <c:when test="#{tareaController.configuracionEnPosicion(x,y) ne null}">
                    <p:column style="width: 80px"
                              colspan="#{tareaController.configuracionEnPosicion(x,y).colSpan}"
                              rowspan="#{tareaController.configuracionEnPosicion(x,y).rowSpan}">
                        <p:outputLabel value="#{tareaController.atributoEnPosicion(x,y).labelAtributo}:"
                                       rendered="#{!tareaController.validar.isBoton(tareaController.atributoEnPosicion(x, y).tipoAtributosOpcionales)}">
                            <c:if test="#{tareaController.configuracionEnPosicion(x,y).esObligatorio}">
                                *
                            </c:if>
                        </p:outputLabel>
                    </p:column>
                    <p:column colspan="#{tareaController.configuracionEnPosicion(x,y).colSpan}"
                              rowspan="#{tareaController.configuracionEnPosicion(x,y).rowSpan}">
                        <c:choose>
                            <c:when test="#{tareaController.validar.isSeparador(tareaController.atributoEnPosicion(x, y).tipoAtributosOpcionales)}">
                                <p:separator/>
                            </c:when>
                            <c:when test="#{tareaController.validar.isNumerico(tareaController.atributoEnPosicion(x,y).tipoAtributosOpcionales)}">
                                <pe:inputNumber decimalSeparator="#{tareaController.configuracionEnPosicion(x,y).separadorDecimal}"
                                                thousandSeparator="#{tareaController.configuracionEnPosicion(x,y).separadorMiles}"
                                                decimalPlaces="#{tareaController.configuracionEnPosicion(x,y).cantidadDecimales}"
                                                disabled="#{mFuncion.soloLectura || !tareaController.tareaAceptada || tareaController.tomadaPorOtroUsuario || tareaController.configuracionEnPosicion(x,y).soloLectura}"
                                                maxValue="#{tareaController.configuracionEnPosicion(x,y).valorMaximo}"
                                                rendered="#{!tareaController.configuracionEnPosicion(x,y).ocultarAtributo}"
                                                value="#{tareaController.atributoEnPosicion(x,y).valorAtributoNumerico}"
                                                style="width: #{tareaController.configuracionEnPosicion(x,y).ancho}px; height: #{tareaController.configuracionEnPosicion(x,y).alto}px;">
                                    <p:ajax global="false" update=":f_tarea:tabView:tab_#{tareaController.indiceTramite}:nombreRepetido, :f_tarea:b_completarT" listener="#{tareaController.validarTarea()}"/>
                                </pe:inputNumber>
                            </c:when>
                            <c:when test="#{tareaController.validar.isBoton(tareaController.atributoEnPosicion(x, y).tipoAtributosOpcionales)}">
                                <p:commandButton value="#{tareaController.atributoEnPosicion(x,y).labelAtributo}"
                                                 actionListener="#{tareaController.ejecutarWs(tareaController.configuracionEnPosicion(x,y))}"
                                                 update=":f_tarea:tabView:tab_#{tareaController.indiceTramite}:pg_funcion_#{tareaController.indiceTramite}"/>
                            </c:when>
                            <c:when test="#{tareaController.validar.isFecha(tareaController.atributoEnPosicion(x,y).tipoAtributosOpcionales)}">
                                <p:calendar value="#{tareaController.atributoEnPosicion(x,y).valorAtributoFecha}"
                                            maxdate="#{tareaController.configuracionEnPosicion(x,y).fechaMaxima}"
                                            mindate="#{tareaController.configuracionEnPosicion(x,y).fechaMinima}"
                                            rendered="#{!tareaController.configuracionEnPosicion(x,y).ocultarAtributo}"
                                            disabled="#{mFuncion.soloLectura || !tareaController.tareaAceptada || tareaController.tomadaPorOtroUsuario || tareaController.configuracionEnPosicion(x,y).soloLectura || tareaController.atributoEnPosicion(x,y).bloquear}"
                                            size="20"
                                            pattern="#{tareaController.configuracionEnPosicion(x,y).formatoFecha}">
                                    <p:ajax global="false" update=":f_tarea:tabView:tab_#{tareaController.indiceTramite}:nombreRepetido, :f_tarea:b_completarT" listener="#{tareaController.validarTarea()}"/>
                                    <p:ajax event="dateSelect" global="false" update=":f_tarea:tabView:tab_#{tareaController.indiceTramite}:nombreRepetido, :f_tarea:b_completarT" listener="#{tareaController.validarTarea()}"/>
                                </p:calendar>
                            </c:when>
                            <c:otherwise test="#{tareaController.validar.isAlfanumerico(tareaController.atributoEnPosicion(x,y).tipoAtributosOpcionales)}">
                                <p:inputTextarea value="#{tareaController.atributoEnPosicion(x,y).valorAtributoAlfanumerico}"
                                                 disabled="#{mFuncion.soloLectura || !tareaController.tareaAceptada || tareaController.tomadaPorOtroUsuario || tareaController.configuracionEnPosicion(x,y).soloLectura}"
                                                 rendered="#{!tareaController.configuracionEnPosicion(x,y).ocultarAtributo}"
                                                 style="width: #{tareaController.configuracionEnPosicion(x,y).ancho}px;
                                                 height:  #{tareaController.configuracionEnPosicion(x,y).alto}px;
                                                 word-break: normal;">
                                    <p:ajax global="false" update=":f_tarea:tabView:tab_#{tareaController.indiceTramite}:nombreRepetido, :f_tarea:b_completarT" listener="#{tareaController.validarTarea()}"/>
                                    <p:ajax event="select" global="false" update=":f_tarea:tabView:tab_#{tareaController.indiceTramite}:nombreRepetido, :f_tarea:b_completarT" listener="#{tareaController.validarTarea()}"/>
                                </p:inputTextarea>
                            </c:otherwise>
                        </c:choose>
                    </p:column>
                </c:when>
                <c:otherwise>
                    <p:column>
                        <h:panelGroup/>
                    </p:column>
                    <p:column>
                        <h:panelGroup/>
                    </p:column>
                </c:otherwise>
            </c:choose>
        </c:forEach>

The idea is that I can configure that page and place the components in the position I want with lots of different configurations. It work pretty fine and people is happy with that, but I'm not. If you check on the page I call the methods configuracionEnPosicion(x,y) and atributoEnPosicion(x,y) like 300 times on every run on the cycle. And these methods call like other 3 methods and do a foreach for find the actual configuration in x,y. Amazingly it doesn't work slow but I feel like that's a lot of overhead that I can avoid.
Before I tried to save the result of configuracionEnPosicion(x,y) and atributoEnPosicion(x,y) in a variable on the client side with their respective getter and setter, but since the JSTL Core tag runs on build time, in rendering time that variable was not updated, resulting in that variable keeping its last value and giving a not desired behavior. My "solution" was the actual one, but my final question is: Is there a way to store the value of that variable so I'd could only keep it alive during build time or something like that? I'd like to call these methods just ONCE per every x and y position, but my knowledges on JSF and Primefaces are not enough to achieve that.
Aditional information:

*

*Apache Tomcat 7.0.41.

*JSF 2.2

*Primefaces 4.0

*Mojarra 2.7.2

*jstl-1.2

A: It looks like task for JSR 107: JCACHE - Java Temporary Caching API. But you should use CDI beans instead of JSF managed beans. This allows you write code like this:
 @CacheResult(cacheName = "configuracionEnPosicion")
 public String configuracionEnPosicion(int x, int y){
    .....
 }

Also it is necessary create META-INF/beans.xml:
 <beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <interceptors>
         <class>org.jsr107.ri.annotations.cdi.CacheResultInterceptor</class>
         <class>org.jsr107.ri.annotations.cdi.CachePutInterceptor</class>
         <class>org.jsr107.ri.annotations.cdi.CacheRemoveEntryInterceptor</class>
         <class>org.jsr107.ri.annotations.cdi.CacheRemoveAllInterceptor</class>
    </interceptors>
</beans>

Also it is necessary create cache somewhere:
@PostConstruct
public void init() {
    try {
        // Retrieve the system wide cache manager
        CacheManager cacheManager = Caching.getCachingProvider().getCacheManager();
        // Define a named cache with default JCache configuration
        MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
        //specify expiry policy
        configuration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
        cache = cacheManager.createCache("configuracionEnPosicion", configuration);
    } catch (Exception e) {
        L.error("Can't init cache!", e);
    }
}

And of course you should select jcache provider (ecache, infinispan, ...) and add necessary dependencies to project.

A: I have EDIT my answer after @BalusC comments
You could precalculate all the values in the backing bean PostConstruct method.

*

*Declare a bidimensional array at backing bean level:
private ReturnedObjectClass[][] precalculatedArray;

*Add the getter method.

*Initialize it in the PostConstruct  method:
precalculatedArray = new ReturnedObjectClass[x][y];

*Populate it with the objects returned by your function in the PostConstruct method:
precalculatedArray[i][j] = myBigFunction(i,j);

Then you can access the calculated values from your page using:
    value="#{tareaController.precalculatedArray[x][y].propertyOfReturnedObjectClass}"

A: You could use c:set.
<c:set var="salary" scope="request" value="#{calculatePosition(x,y)}"/>

or maybe you could use varstatus depending on what happens in your fct. (this is the doc for a jsf tag not a jstl tag but it's the same thing).


text:
Q: What exactly does lazy evaluation mean in the context of the dplyr r package, and when shouldn't I use it? I recently read the Non-standard evaluation chapter from the dplyr vignette, after I'd come across dplyr functions that end on _. Having heard an introduction into Haskell a long time ago, I roughly remember "lazy evaluation" as a term for "evaluation of code, but only if or when it is really necessary to do so" - and reading the lazy evaluation chapter form Hadley Wickham's Advanced R seemed to confirm that memory.
What I don't seem to be able to wrap my head around however is what NSE/SE (lazy/eager evaluation) is used for in dplyr and when e.g. functions like  summarize_() are used in comparison to summarize().
Maybe I missed a part of documentation somewhere. I'd be happy to narrow down the topic of my question, or even roll back if it becomes clear that the question is too broad or has already been answered here.


text:
Q: Codeigniter Query result returning Custom result object with setters How exactly does CI custome object works ?
As per CI documentation You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");

foreach ($query->result('User') as $row)
{
   echo $row->name; // call attributes
   echo $row->reverse_name(); // or methods defined on the 'User' class
}
}

This is a very nice feature yet what Ci does is it will return an array of User objects and set attributes from row to it.
i have a problem with it that i want to have more control on what attributes to be publicly accessed and what to be modified before setting/getting.
how can i accomplish this ? can i tell CI to pass all attributes to constructor so that class can populate its own data ?
example class User
class User{
    private $data=array();
    protected $CI;
    //public $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;
    function __construct($data=null)
    {
        $this->data = $data; // i want to save data to a private var and allow attr. throu getters only
    }
    function set_password($p){
      $this->generateSalt();
      $this->data->password = $p.$this->data->salt;
    }
}

In a nutshell::
I want to use custom_result_object but i dont want codeigniter to populate class attributes for me, instead i want the class to receive those attrs and populate it him self the way he this its appropriate.

A: I found your question while looking for a solution for myself.
After digging a bit in the documentation I managed to figure it out:
class user_item {
  // you can declare all the attributes you want as private
  private $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;

  function __construct(){
    // you can use the constructor to format data as needed
    $this->username = strtouppper($this->username);
  }

  public function set_password($p){
    $this->generateSalt();
    $this->password = $p.$this->salt;
  }

  public function get_password(){
    return $this->password;
  }
}

Once set up, you can instantiate this class from $this->db->result()
class User_model extends CI_Model {
   public function get_user($id){
     return $this->db->get_where('users', array('id' => $id), 1)->result('user_item');
   }
}

And call any public method or attribute of the class as needed
class Users extends CI_Controller {
  function __construct(){
     $this->load->model('user');
  }
  public function profile($user_id){
    var $myUser = $this->user->get_user($user_id);
    $myUser->set_password('myPassword');
    echo $myUser->get_password();
  }
}

I have simplified the code to make it clearer, but you get the idea.

A: this example controller using result array and object
if ($this->session->userdata('id_jurusan') ==1) {
            $where=array('id_jurusan'=>$this->session->userdata('id_jurusan'));
            $value = $this->session->userdata('id_jurusan');
            $value2 = $this->session->userdata('username');
            $data['rule']=$this->guru_mod->get_where($where,'forward_changing')->result();
            $data['fuzzy']=$this->guru_mod->get_data_all('fuzzy')->result();
            $data['artikel']=$this->guru_mod->get_data_all('artikel')->result();
            $data['kondisi']=$this->guru_mod->get_where($where,'kondisi')->result();
            $data['artikel2'] = $this->guru_mod->get_data_all2('artikel','id_jurusan',$value);
            $data['riwayat_rule'] = $this->guru_mod->get_data_all2('forward_changing','username',$value2);
            $data['kondisi_rule'] = $this->guru_mod->get_data_all2('kondisi','id_jurusan',$value);
            $this->load->view('guru/daftar_rule',$data);
        }


text:
Q: adding items in an array in assembly I'm writing in Assembly on a Mac book and I'm having a problem adding items in an array.
I need to get the average of the items in the array. Any help is greatly appreciated.
A few of the comments might say 5 but I've switched it to take in 10 numbers and just didn't change them yet. I think it has something to do with the way I'm loading the numbers from the array but I'm not sure.
.text
    .globl main
main:

la $t0, array    # load address of array into $t0
li $t1, 10        # size of array is 5 (0 - 4)
li $t3, 0        # initialize counter to zero
li $t6, 0

#Populate the array

while:
la $a0, intPrompt        #prompt for integer
li $v0,4                 #a0 = address of string
syscall                  #v0 = 4, indicates display a String

li $v0,5                 # enter input -> v0
syscall                  # 5 is sys call for read int

sw $v0, ($t0)

add $t0,$t0,4            # move pointer ahead to next array element
add $t3,$t3,1            # increment counter

blt $t3,$t1,while        # branch to while if counter < size of array

# End While to populate the array
wend:

la $a0,title        # Display "Array: "
li $v0,4            # a0 = address of message
    syscall

# Loop to print array values

li $t0, 0           # initilize array index value back to 0
li $t3, 0           # initial size counter back to zero
la $t0, array       # load address of array back into $t0

startPrint:

lw $t2,($t0)        # load word a[i] into temp (t2)
move $a0, $t2       # move a[i] to a0 for display
li $v0,1            # display a[i]
syscall

la $a0,comma        # Display ", "
li $v0,4            # a0 = address of message
syscall             # v0 = 4 which indicates display a string

add $t0,$t0,4       # move pointer ahead to next array element
add $t3, $t3, 1     #increment counter

blt $t3,$t1,startPrint     # branch to startPrint if counter < size of array

endPrint:     # End loop to print array values

startAdd:

lw $t2,($t0)
move $a0,$t2

add $t6, $t6, $t0

add $t0, $t0,4
add $t3, $t3, 1

blt $t3, $t1,startAdd

endAdd:

move $a0, $t6
li $v0, 1
syscall

la $a0,crlf         # Display "cr/lf"
li $v0,4            # a0 = address of message
syscall             # v0 = 4 which indicates display a string

li $v0,10           # End Of Program
syscall

.data

intPrompt:  .asciiz   "Enter an Integer: "   # hold the prompt message for each int in the array
title:      .asciiz   "\nArray: "
crlf:       .asciiz   "\n"
comma:      .asciiz   ", "

array:      .word 40  # 5 words


text:
Q: Deploy quietly to Google Play Is it possible to release a public application through Google Play without any public notification?  We want to publish an app on Google Play that isn't seen by any marketing robots that generate "What's New in Android"-type articles.

A:
Is it possible to release a public application through Google Play without any public notification?

No. There are private deployment options, such as for enterprise apps. But if the public can access it, then you have no means of preventing "marketing robots" from accessing it, any more than you can prevent people of races, religions, political parties, or anything else you don't like from accessing it.
You're welcome to attempt to pressure Google to cut off access to these "marketing robots", which use undocumented, unsupported, and possibly unauthorized means of determining "what's new". I have lobbied to either make this capability officially allowed or officially disallowed, rather than have it reside in the grey area that it does presently, to no avail.