text:
Q: Collection was modified; enumeration operation might not execute in LinQ I get data from a site and insert to DataTable dt.
if (checked = true)
{
    while (true)
    {
        breakIt = true;
        try
        {
            string html = browser_array[idx].FindElementByXPath("id('tabbox')").GetAttribute("outerHTML");
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            HtmlNodeCollection nodesMatchingXPathlop = doc.DocumentNode.SelectNodes("//*[contains(@class,'tabbox_F')]/table/tbody/tr");
            if (nodesMatchingXPathlop.Count == 0)
            {
                break;
            }
            else
            {
                for (int j = 0; j < nodesMatchingXPathlop.Count; j++)
                {
                    try
                    {
                        listHeader[1].Clear();
                        HtmlNodeCollection listTD3 = nodesMatchingXPathlop[j].SelectNodes("td");
                        if (nodesMatchingXPathlop[j].SelectNodes("td").ToString() == "")
                            return;
                        if (nodesMatchingXPathlop[j].SelectNodes("td").Count == 10)
                        {
                            if (listHeader[1].Count == 0)
                                continue;
                            else
                                Insert(dt, listHeader[1]);
                        }
                        else
                        {
                            continue;
                        }
                    }
                    catch (Exception ex) { throw; }
                }
            }
            if (breakIt)
            {
                break;
            }
        }
        catch (Exception ex) { throw; }
    }
}

So, this function is Insert(DataTable dt, List<String> listHeader):
static void Insert(DataTable dt, List<String> listHeader)
{
    DataRow row = dt.NewRow();
    string[] array = listHeader.ToArray();
    string newArray = "";
    newArray = Regex.Replace(array[1], @"\s+", " ");
    string arrayHindiCap2 = "";
    arrayHindiCap2 = Regex.Replace(array[2], @"\s+", " ").Replace(" ", "");
    string arrayHindiCap5 = "";
    arrayHindiCap5 = Regex.Replace(array[5], @"\s+", " ").Replace(" ", "");

    try
    {
        if (!string.IsNullOrWhiteSpace(arrayHindiCap2))
        {
            InsertCondition(arrayHindiCap2, arrayHindiCap5, newArray, listHeader, array);
        }
        else if (!string.IsNullOrWhiteSpace(arrayHindiCap5))
        {
            InsertCondition(arrayHindiCap2, arrayHindiCap5, newArray, listHeader, array);
        }
    }
    catch (Exception ex) { throw; }
}

I have a table like this:
Option         B0_1           Col 1            Col 2

op1            10             89

I will get an index of rows in DataTable when it correct with a condition.
static void InsertCondition(string arrayHindiCap2, string arrayHindiCap5, string newArray, List<String> listHeader, string[] array)
{
    try
    {
        index = dt.AsEnumerable()
             .Select((rowF, idx) => new { rowF, idx })
             .Where(item =>
              GetFirstB(numB) == (item.rowF.Field<string>("B0_1") != null ? item.rowF.Field<string>("B0_1") : "") &&
              GetFirstWord(optionString) == (item.rowF.Field<string>("Option") != null ? item.rowF.Field<string>("Option") : ""))
             .Select(item => item.idx)
             .ToArray();
        }
        catch(Exception ex) { throw; }
}

I define GetFirstB() and GetFirstWord():
private static string GetFirstWord(string str)
{
    try
    {
        return string.Concat(str.Split(' ').Take(2));
    }
    catch (Exception ex) { throw; }
}

private static string GetFirstB(string str)
{
    try
    {
        if (str == null)
            return null;
        if (str.Equals(" "))
            return null;
        string[] strNew;
        strNew = str.Split(' ');
        strNew = strNew.Where(c => c != "").ToArray();
        return string.Concat(strNew.FirstOrDefault());
    }
    catch (Exception ex) { throw; }
}

Following @ScottChamberlain and @PhilipKendall suggest.
I edit my code and tried debug again.
After Copy exception copies detail to clipboard it shows like this:
System.InvalidOperationException was caught
  HResult=-2146233079
  Message=Collection was modified; enumeration operation might not execute.
  Source=System.Data
  StackTrace:
       at System.Data.RBTree`1.RBTreeEnumerator.MoveNext()
       at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
       at System.Linq.Enumerable.<SelectIterator>d__7`2.MoveNext()
       at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
       at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
       at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
       at LAPSOFT.Program.InsertCondition(String arrayHindiCap2, String arrayHindiCap5, String newArray, List`1 listHeader, String[] array) in d:\lapsoft-project\CA CUOC - Copy\Program.cs:line 418
       at LAPSOFT.Program.Insert(DataTable dt, List`1 listHeader) in d:\project\CheckCopy\Program.cs:line 548
  InnerException:


text:
Q: Bash script curl return value within a script I'm a stumped here.  I have a simple script that checks to see if end-point is available via curl command. It checks the return value and if the value is not '0', it exists. Here is a sample:
url="http://xxy.bb.cc.com:7799"
curl -Is $url > /dev/null 2&>1
retVal=$?
[[ $retVal -ne 0 ]] &&  echo "$url is not accessible"  && exit $retVal

When I execute the command from within my script it returns a non-zero value but when I ran the same sequence of commands manually off my terminal (Mac OS), it works and returns 0.
Any idea why ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I deploy from the drop location given a specific build number using TFS Trying to implement CI using TFS.  I have the builds working fine and the projects are all nicely split up in the drop folder.  My question is, how can I allow the QA team queue up a deployment "build" (no actual building going on) where they can give a specific build number.  This build number is then used to deploy the bits in that specific build drop folder.
The ultimate goal is to give them a couple of parameters on the queue build dialog (done that already) and then start the deployment process.  I thought of using TFS Deployer, tried creating my own deployment process template and then executing a powershell script from the .proj file.  Seems like each option has it's own set of complications.
Can anyone give me some guidance on the best way to accomplish this?

A: I did this recently using the following:

*

*Select the deployment target (selects machine, site, multiple configuration item data).

*Custom .config file transformations to match deployment target (connection strings etc.).

*Exec task for MSDeploy to get the build to the server using Web Deploy 2.0.

*PSExec executing an appcmd command remotely on the server to restart the specific site

*Repeat for services, push with MSDeploy.

*Build script generates install/uninstall scripts for services.

*PSExec for services (stop, uninstall, install, start).

This was kept isolated in an MSBuild file, which can be executed from any command line passing in the build drop number, or can be added to the TFS build definition with an MSBuild task, keyed off of the extra parameters you've already set up.

A: The way to do this is to trigger the deployment on a change in build quality. The idea is that when the quality is changed to "Ready for QA" for instance, a change event triggers to deploy from the existing build folders to the QA system.
See Publish to FTP after TFS 2010 build quality change and Auto-Deployment Using Microsoft Web Deploy on Build Quality Change Event of TFS 2010.

A: You can limit the users who have permissions to kick off a build and through this give the rights to kick off a manual build to your QA team.
In your TFS build script you can create the deployment steps needed for your QA team. By default you would make it conditional based on a parameter and have it set to not deploy. You could make this true or false depending on if it is a CI build or a manual build.
When you are ready to have your code tested by QA you give them the label to use and they would just have to pass it in and would be able to build and deploy it.
The beauty of this is you control which signed off version of code you are ready to hand off to your QA team.
You also have a report that lists the specific code and work items that were handed off to QA.


text:
Q: Cant override UIButton titleLabel properties from button outlet programmatically So i am using size classes in my storyboard. The button is in my storyboard is using autolayout and its fine and all.
I made an outlet to my ViewController and i am trying to change the title label text and text color, neither of which are working. However, the corner radius and background color are working.
  @IBOutlet weak var cancelButton_iPhone: UIButton!

  func setupButtons() {
    cancelButton_iPhone.layer.cornerRadius = 8.0
    cancelButton_iPhone.backgroundColor = UIColor(red:1, green:1, blue:1, alpha:0.15)
    cancelButton_iPhone.titleLabel?.textColor = UIColor.white
    cancelButton_iPhone.titleLabel?.text = "testtest"
  }

setupButtons() is being called in ViewWillAppear. Ive tried ViewDidLoad as well and no difference.
In the storyboard, the cancelButton_iPhone text is set to "Cancel" and the textcolor is set to Yellow. And this is what is being reflected in my app.  Instead of the "testtest" and white text.
Thanks

A: The property return title views,will always create them if necessary,and always returns nil for system buttons.And UIButton is subclass of UIControl,so you always need to specify ControlState when updating button's title! You can call the func    setTitle(_ title: String?, for state: UIControlState) to set button's title,so does button's titleColor.

A: For button titles you should use these methods.
func setTitleColor(_ color: UIColor?, for state: UIControlState)
func setTitle(_ title: String?, for state: UIControlState)

A: Try adding below code:
@IBOutlet weak var cancelButton_iPhone: UIButton!

func setupButtons() {
    cancelButton_iPhone.layer.cornerRadius = 8.0
    cancelButton_iPhone.backgroundColor = UIColor(red:1, green:1, blue:1, alpha:0.15)
    cancelButton_iPhone.setTitle("testtest", for: .normal)
    cancelButton_iPhone.setTitleColor(UIColor.white, for: .normal)
}

Hope it helps.


text:
Q: Encoding a password with the Spring Security Grails plugin In my Grails 2.5.1 project, I'm using the spring-security-core:2.0-RC5 plugin and getting this error:
Error initializing the application: Cannot invoke method encodePassword() on null object

Here is my BootStrap :
class BootStrap {

    def init = { servletContext ->
        def springSecurityService
        def userRole = SecurityRole.findByAuthority("ROLE_USER") ?: new SecurityRole(authority:"ROLE_USER").save(flush:true)
        def adminRole = SecurityRole.findByAuthority("ROLE_ADMIN") ?: new SecurityRole(authority:"ROLE_ADMIN").save(flush:true)

        def user = new User(username:"user" ,password:springSecurityService.encodePassword("123"),enable:true ).save(flush:true)
        def admin = new User(username:"admin" ,password:springSecurityService.encodePassword("1234"),enable:true ).save(flush:true)
        SecurityUserSecurityRole.create(user, userRole)
        SecurityUserSecurityRole.create(admin, adminRole)
    }
    def destroy = {
    }
}

Anything I'm missing?

A: The problem is the location of def springSecurityService. As you have it declared, it's a local variable of the init closure. It's not a candidate for dependency injection, so nothing initializes it and it's null.
To use dependency injection, declare beans as class-scope properties, not local variables (of closures or methods). The reason that this works is that the Groovy compiler converts a property declaration into a private field with a getter and a setter. Spring doesn't have any support for Groovy properties, but can autowire by name (and this is the Grails default) when there's a setter method that coincides with the bean name. So since the Groovy compiler adds a void setSpringSecurityService(springSecurityService) method for you, Spring sees it and invokes it since the method's "property" name matches the bean you want. If you declare a local variable, it's completely ignored.
So your code should look like this:
def springSecurityService

def init = { servletContext ->
    ...
}

But then you'll hit the second problem with your code. Assuming you haven't changed the auto-hashing logic in your User class, you'll be encoding twice. Once in BootStrap, and again in the domain class. If you do this nobody will be able to authenticate. Pick one - hash explicitly like you're doing and remove the code from the domain class, or leave the domain class code and just set the cleartext password. If you choose option #2, your code (also cleaned up to use findOrSaveBy and to replace all of those unnecessary eager flush calls with one) should look like
class BootStrap {

    def init = {
        def userRole = SecurityRole.findOrSaveByAuthority('ROLE_USER')
        def adminRole = SecurityRole.findOrSaveByAuthority('ROLE_ADMIN')

        def user = new User(username: 'user' ,password: '123').save()
        def admin = new User(username: 'admin' ,password: '1234').save()
        SecurityUserSecurityRole.create(user, userRole)
        SecurityUserSecurityRole.create(admin, adminRole)

        User.withSession { it.flush() }
    }
}

An even better approach would be to move this code to a transactional service. This is left as an exercise for the reader.


text:
Q: Code works fine on JAVA But Fails to Create Decrypted File on Android I was trying to make a file File Locker App for Android. For encryption & Decryption I used some code which I previously tested on JAVA. It works fine on JAVA, But Fails to Create The Decrypted File on Android platform.
My Code is something like bellow,
public class Cryptographer {
private static final String ALGORITHM = "AES";

private final static String ALGO_RANDOM_NUM_GENERATOR = "SHA1PRNG";

public static int encrypt(String key, File inputFile, File outputFile)
        throws CryptographyException {
    if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdir();
    return StartCryptography(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}

public static int decrypt(String key, File inputFile, File outputFile)
        throws CryptographyException {
    if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdir();
    return StartCryptography(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}

private static int StartCryptography(int cipherMode, String key, File inputFile,
                                     File outputFile) throws CryptographyException {
    int performance = -1;
    try {
        SecureRandom random = SecureRandom.getInstance(ALGO_RANDOM_NUM_GENERATOR);
        random.setSeed(key.getBytes());
        KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
        generator.init(random);
        SecretKey key1 = generator.generateKey();

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(cipherMode, key1);

        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length()];
        inputStream.read(inputBytes);

        byte[] outputBytes = cipher.doFinal(inputBytes);

        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(outputBytes);

        inputStream.close();
        outputStream.close();
        performance = 1;

    } catch (NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidKeyException | BadPaddingException
            | IllegalBlockSizeException | IOException ex) {
        throw new CryptographyException("Error encrypting/decrypting file", ex);
    } finally {
        return performance;
    }

 }
}

I am using a button which when pressed All Files From a declared Array Should First be encrypted, and then the encrypted file will be decrypted to another location. But no Decrypted file is created.
My onClick Method of the button looks like bellow,
public void onKeyDown1(View view) throws CryptographyException {

        File outfile = new File(ExternalStorageDirectoryPath, "Encrypted");
        File outfileDec = new File(ExternalStorageDirectoryPath, "Decrypted");
        for (MyFiles f : files) {
            if (f.getCheckstate()) {
                File EncFile=new File(outfile,f.getName());
                //File DecFile=new File(outfileDec,f.getName());

                Cryptographer.encrypt(key, f, EncFile);

                Cryptographer.decrypt(key, EncFile, DecFile);

            }

        }
}

Someone please help me..!!
The ExternalStorageDirectoryPathis a String retrieved by Calling Environment.getExternalStorageDirectory().getAbsolutePath(); .
And MyFiles Class is
public class MyFiles extends File {

boolean Checkstate=false;

public MyFiles(File dir, String name) {
    super(dir, name);
}

public MyFiles(String path) {
    super(path);
}

public MyFiles(String dirPath, String name) {
    super(dirPath, name);
}

public MyFiles(URI uri) {
    super(uri);
}

public void setCheckstate(boolean checkstate) {
    Checkstate = checkstate;
}

public boolean getCheckstate(){
    return Checkstate;
}

public MyFiles[] listFiles(FileFilter filter) {
    MyFiles[] files = listFiles();
    if (filter == null || files == null) {
        return files;
    }
    List<MyFiles> result = new ArrayList<MyFiles>(files.length);
    for (MyFiles file : files) {
        if (filter.accept(file)) {
            result.add(file);
        }
    }
    return result.toArray(new MyFiles[result.size()]);
}

public MyFiles[] listFiles() {
    return filenamesToFiles(list());
}

private MyFiles[] filenamesToFiles(String[] filenames) {
    if (filenames == null) {
        return null;
    }
    int count = filenames.length;
    MyFiles[] result = new MyFiles[count];
    for (int i = 0; i < count; ++i) {
        result[i] = new MyFiles(this, filenames[i]);
    }
    return result;
}

}

A: I suppose it might be lack of permissions in Manifest file of your android app. Check: http://developer.android.com/guide/topics/manifest/manifest-intro.html
 Or you are trying to write in  a location your app is not allowed


text:
Q: Fluent NHibernate - Mapping one-to-many using 2 columns I have a db schema along the lines of:
Product

*

*ID

*ProductName

*Description

*StoreBrand

ProductVariation

*

*VariationID

*ProductID

*Size

*StoreBrand

*Price

Classes, predictably, look a bit like this:
public class Product
{
  public virtual int ID { get; set; }
  public virtual string ProductName { get; set; }
  public virtual string Description { get; set; }
  public virtual string StoreBrand { get; set; }

  public virtual IEnumerable<ProductVariation> Variations { get; set; }
}

public class ProductVariation
{
  public virtual int VariationID { get; set; }
  public virtual int ProductID { get; set; }

  public virtual Product Product {get; set;}

  public virtual string Size { get; set; }
  public virtual double Price { get; set; }
}

I've got the mapping classes like this:
public class ProductMapper : ClassMap<Product>
{
  public ProductMapper()
  {
    Id(x => x.ID);
    Map(x => x.ProductName);
    Map(x => x.Description);
    Map(x => x.StoreBrand);

    HasMany(x => x.Variations)
      .KeyColumn("ProductID");
  }
}

public class ProductVariationMapper : ClassMap<ProductVariation>
{
  public ProductVariation()
  {
    Id(x => x.ID);
    Map(x => x.ProductID);
    Map(x => x.Size);
    Map(x => x.Price);

    References(x => x.Product)
      .Column("ProductID");
  }
}

This is kind of working...
However, what I need to do is tie the Product.Brands together with the ProductVariation.Brands as well... (and vice versa)
So querying Product, returns a list of it's ProductVariations for that brand...
(Notice, ProductVariation doesn't have a property in the class, but it has the column for mapping)
ProductVariation.ID is non unique.
The key is ProductVariation.ID and ProductVariation.Brand (on the database)

A: public class Product
{
    public virtual int ID { get; set; }
    public virtual string StoreBrand { get; set; }

    public virtual string ProductName { get; set; }
    public virtual string Description { get; set; }

    public virtual IEnumerable<ProductVariation> Variations { get; set; }

    public override Equals(object obj)
    {
        return Equals(obj as Product)
    }

    public override Equals(Product other)
    {
        return (other != null) && (Id == other.Id) && (StoreBrand == other.StoreBrand);
    }

    public override GetHashCode()
    {
        unchecked
        {
            return Id.GetHashCode() * 397 + StoreBrand.GetHashCode();
        }
    }
}

public class ProductVariation
{
    public virtual int ID { get; set; }

    public virtual Product Product {get; set;}

    public virtual string Size { get; set; }
    public virtual double Price { get; set; }
}

public class ProductMapper : ClassMap<Product>
{
    public ProductMapper()
    {
        // Id alone is not unique, hence compositeId
        CompositeId()
            .KeyProperty(x => x.ID)
            .KeyProperty(x => x.StoreBrand);

        Map(x => x.ProductName);
        Map(x => x.Description);

        HasMany(x => x.Variations)
            .KeyColumn("ProductID", "StoreBrand");
    }
}

public class ProductVariationMapper : ClassMap<ProductVariation>
{
    public ProductVariation()
    {
        Id(x => x.ID);

        Map(x => x.Size);
        Map(x => x.Price);

        References(x => x.Product)
            .Column("ProductID", "StoreBrand");
    }
}


text:
Q: Firebug style code inspector for iPhone / iPad? Im testing a website ive made and there are some differences in how the site looks on iPhone and iPads compared to desktop browsers (including webkit browsers like Safari and Chrome).
I need have a look at the styes like i can do with Firebug or the Chrome dev tools, but for iPads or iPhones. What are the options for doing this?

A: On iPhone/iPad enter Settings, then Safari, go to Developer and turn on Debug Console.
Next, you need to connect your iPhone/iPad to apple computer. Then on computer enter Safari application. In safari enter Development tab and select your device. Web Inspcetor will show up, with code of selected page.

A: Chrome can now do device emulation:
Open the dev tools.
Get to the emulation tab (I got here by going 'show console', then the emulation tab is under the normal elements inspector).
Now you can chose from a number of different devices, and you can still use the html / css inspector.


text:
Q: OpenCL compiler preprocessing definitions? I am developing OpenCL code on Snow Leopard and understand that the OpenCL just-in-time compilation is done by Clang/LLVM. Is the C preprocessor used at all? Is there a way to set preprocessing definitions with the compiler? What definitions exist?
I would like the code to be aware of whether it is compiled for CPU or GPU so I for instance can use printf statements for debugging.

A: the clBuildProgram API takes compiler arguments (the const char * options parameter).
-D MYMACRO is understood, so is -D MYMACRO=value.
As to what predefined macros, see the OpenCL specification for a full list (Section 6.9). A non exhaustive list:

*

*__FILE__

*__LINE__

*__OPENCL_VERSION__

A: You can also use the OpenCL "preprocessor" to define definitions (like in C):
#define dot3(x1, y1, z1, x2, y2, z2) ((x1)*(x2) + (y1)*(y2) + (z1)*(z2))

(notice the brackets, they are important because you can insert any Expression in the Variables and the expression gets correctly evaluated)
This helps to improve the speed of your Application.


text:
Q: How to Nested Categories in django admin I want to create muti category in my ecommerce website where sub category will be dependent on main category.
Please help me with this
 class MainCategory(models.Model):
#     name = models.CharField(max_length=50)
#     date_created = models.DateTimeField(auto_now_add=True)

#     def __str__(self):
#         return self.name

# class SubCategory(models.Model):
#     perentcategory = models.OneToOneField(MainCategory, on_delete=models.CASCADE, primary_key=True)
#     name = models.CharField(max_length=50)
#     date_created = models.DateTimeField(auto_now_add=True)

#     def __str__(self):
#         return self.name

# class Items(models.Model):
#     main = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
#     name = models.CharField(max_length=255)

Posting this question 4th time

A: Change models.OneToOneField to models.ForeignKey so you can have multiple subcategories assigned to a main category:
class MainCategory(models.Model):
     name = models.CharField(max_length=50)
     date_created = models.DateTimeField(auto_now_add=True)

     def __str__(self):
         return self.name

 class SubCategory(models.Model):
     main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, primary_key=True)
     name = models.CharField(max_length=50)
     date_created = models.DateTimeField(auto_now_add=True)

     def __str__(self):
         return self.name

 class Items(models.Model):
     main = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
     name = models.CharField(max_length=255)

A: You can use single model to accommodate both Category and Sub-categories. Something like this.
class Category(models.Model):
    name = models.CharField(blank=False, max_length=200)
    slug = models.SlugField(null=False)
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.SET_NULL)

Then add following function to the above model
def get_categories(self):
         if self.parent is None:
              return self.name
         else:
             return self.parent.get_categories() + ' -> ' + self.name

def __str__(self):
        return self.get_categories()

This will return structure similar to this image


text:
Q: Rails form not working with turbolinks This question seems to be the same as mine: Rails turbolinks break submit remote form
 ( This question is also similar, As is this github issue )
However the answers posted there did not solve my issue...
The issue I am having:
On the users show page there is a simple form to submit new to-do items. The form is setup to use AJAX. The form submit works correctly on initial page load or page refresh. However, it does not work at all (clicking the submit button does nothing, not in rails or with AJAX) after you navigate anywhere within the app. Meaning, once you have navigated out of the show view and back without refreshing the page, clicking the submit button on the form does nothing.
The above quoted issues all seem to suggest that it is an issue with turbolinks, however the answers posted there either did not work, or I could not understand them well enough to fix my issue...
Any help would be amazing!!!
Here is code that may be helpful:
_form.html.erb (rendered in the show view)
<%= form_for [task], remote: true do |f| %>

            <%= f.text_field :name, class: 'form-control', placeholder: "Add new task..." %>

            <%= f.date_field :expires_at, max: Time.now + 7.days, min: Time.now + 1.day %>

            <%= f.submit "Save", class: 'btn btn-success' %>

<% end %>

create method in TasksController
def create
    expires_at_format unless params[:task][:expires_at].blank? # adds the current time to a user created date

    @task = current_user.tasks.new(task_params)

    if @task.save
        flash.now[:notice] = "\"#{@task.name}\" added to To-Do list!"
    else
        if @task.errors.any?
            flash.now[:alert] = "Task not saved. #{@task.errors.full_messages.join '. ' }."
        else
            flash.now[:alert] = "Something went wrong! Your task was not saved... "
        end
    end

    respond_to do |format|
        format.html { redirect_to root_path }
        format.js
    end
end

create.js.erb (AJAX to handle displaying new tasks)
<% if @task.valid? %>
    $('.task').children('.expires_at').each(function(){
        if ($(this).text() <= "<%= @task.expires_at.to_s %>") {
            $(this).parent().before("<%= escape_javascript(render(@task)) %>");
            return false;
        }
    });
    $('#task_name').val("");
    $('th#task-count').html("You have <%= pluralize(current_user.tasks.unexpired.count, "Task").split.insert(1, "active").join ' ' %>");
    $(".flash").html("
<button type='button' class='close' data-dismiss='alert'>×</button><%= flash.now[:notice] %>
");
<% else %>
    $('#task_name').val("");
    $('.flash').html("
<button type='button' class='close' data-dismiss='alert'>×</button><%= flash.now[:alert] %>
");
<% end %>

from application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require toggleExpired
//= require_tree .

'from gemfile`
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'

A: Have you turned on persist logging in your JS debugger/console (so you can see the console across page loads)? It seems to me like you hare having some sort of JS error that is breaking the execution stack. Specifically, I would look into jquery.turbolinks (It looks like you don't have it installed).
Also, are you 100% confident Turbolinks is causing the issue?  It is fairly easy to disable this specific gem to further isolate the issue.


text:
Q: Create a maven project to be used as a jar library in another project I want that a maven project can be used as a black box jar. This is needed because second project was born its way, and I don't want to integrate its code by hand. So the best way is that this project is going to save it's data on db, but it should use a service offered by the "wrapper" project to save them.
The idea is simple, the secondary project can expose just a method to which I will pass the service that offers the save method as a parameter.
The secondary project should not have configuration files, but should rely on the father application's properties.
Any idea to do this fast and almsot good? Thanks for any suggestion.
EDIT 2013/03/07: The idea behind this is that the second project should generate a classic jar library that looks a properties file into the classpath of the host project. Something like Quartz/Spring/... you import jar and you provide the properties file.

A: I just defined some classes to load properties from the classpath, and some interfaces to make the two projects interact.
In pom.xml of the parent project I imported the child project excluding it's dependencies to avoid conflicts.
It was a pretty easy task at the end.


text:
Q: Ошибка при обращении SslStream Вот Ошибка:
Эта операция допустима только при использовании контекста, подлинность которого успешно подтверждена.
Вот Код Сервера:
using System.Net.Security;
internal static SslStream sslStream;

tcpListener = new TcpListener(IPAddress.Any, 8000);
tcpListener.Start();
TcpClient сlient = tcpListener.AcceptTcpClient();
Stream = client.GetStream();
sslStream = new SslStream(Stream);

string message = Console.ReadLine();
byte[] data = Encoding.Unicode.GetBytes(message);

sslStream.Write(data, 0, data.Length);

Код Клиента:
using System.Net.Security;
internal static SslStream sslStream;

client = new TcpClient();
client.Connect("127.0.0.1", 8000);
stream = client.GetStream();
sslStream = new SslStream(stream);

sslStream.AuthenticateAsClient("127.0.0.1");

string message = userName;

byte[] data = new byte[1024];

sslStream.Read(data, 0, data.Length);

Console.WriteLine(Encoding.Unicode.GetString(data, 0, bytes));

A: Нельзя просто начать читать/писать с SslStream, предварительно нужно вызвать один из методов: AuthenticateAsClient/AuthenticateAsServer. На стороне сервера вы не вызываете ничего, поэтому получаете ошибку.
Что бы всё работало, вам нужно создать/получить сертификат.
Минимальный рабочий пример:
static void Main(string[] args)
{
    var serverThread = new Thread(() =>
    {
        var server = new TcpListener(IPAddress.Any, 12345);
        server.Start();
        var client = server.AcceptTcpClient();
        var ssl = new SslStream(client.GetStream());
        var cert = new X509Certificate2(@"rsa-4096.pfx", "hh87$-Jqo");
        ssl.AuthenticateAsServer(cert);
        ssl.Write(Encoding.ASCII.GetBytes("Hello world"), 0, 11);
        ssl.Flush();
        ssl.Close();
        server.Stop();
    });

    var clientThread = new Thread(() =>
    {
        var client = new TcpClient();
        client.Connect(IPAddress.Loopback, 12345);
        // последний параметр отключает проверку серверного сертификата
        var ssl = new SslStream(client.GetStream(), false, (a, b, c, d) => true);
        ssl.AuthenticateAsClient("localhost");
        using (var sr = new StreamReader(ssl, Encoding.ASCII))
        {
            string recivedText = sr.ReadToEnd();
            Console.WriteLine(recivedText);
        }
    });

    serverThread.Start();
    clientThread.Start();

    serverThread.Join();
    clientThread.Join();
}

Сертификат для примера: https://github.com/Zergatul/ZergatulLib/blob/master/ConsoleTest/rsa-4096.pfx


text:
Q: How is fast-forward implemented in Git so that two branches preserve? In libgit2 headers I read that after fetch, if fast forward is signalized to be available during analysis, then what's needed is simple checkout of the fetched tip (and altering of heads/<branch>). It seemed logical, however I wonder, how can the refs/heads/<branch> be differentiated from remotes/<remote>/<branch> ? Commits have parents embedded in them – that constitutes a single history, while there should be two histories, with additional "Merge" commits in both of them. How is fast-forward implemented then? It really leads to SHA hashes to repeat in both histories, so libgit2 seems to have its point.

A: A "fast forward" isn't a merge at all, it just sets the branch pointer to "their" side of the merge.
Consider some history:
1 -- 2 -- 3 -- 4 -- 5 -- 6

And consider that my master branch is at commit 4, and the server's master branch is at commit 6.
If I wish to do a merge of the parent's master branch into mine (perhaps as part of a pull), the first step of a merge is to find the merge base, or the common ancestor between those two commits.
In this case (above), 4 is the common ancestor between 4 and 6.  So there are no commits locally that the server doesn't have, so you can simply "fast forward" your branch, updating its pointer to point to 6.  You will not have lost any data by doing this (though you will have also not created any - if you had  forced an actual merge with a "no fast forward" option then you would create a new merge commit between 4 and 6.
So libgit2's git_merge_analysis function, which identifies whether a merge can be fast-forwarded or not, literally just checks to see if the "yours" branch is your own common ancestor with the "theirs" branch.
This is, of course, not the typical merge case.  Consider:
             F -- G
            /
A -- B -- C -- D -- E

In this case, if you are at commit G locally and the upstream is at commit E then your common ancestor is C and a fast forward is not possible, you must perform a true merge.

A: Since Git is a CVCS, the local repo and the remote one can be considered logically as one repo. refs/heads/master(r) is refs/heads/master in the remote repo.

The remote master has been updated by others.

Now we want to update the local master with the remote master via git pull origin master.
First git fetch origin master is run internally and remotes/origin/master is updated. This is actually a fast-forward merge. remotes/origin/master moves from C to E.

And then git merge remotes/origin/master is run. refs/heads/master is updated via a fast-forward merge. It moves from C to E too.

If refs/heads/master was updated by us before the pull, it would be a true merge instead. Before the pull it was like

Here we have two options, git pull origin master or git pull origin --rebase master.
The fetch process is the same.

Without --rebase, it would be a true merge.

With --rebase, it would be a rebase.

P could be just ignored now since it's not referred to by any branch or tag now.
Taking the last case for example, if we now push refs/heads/master to the remote, refs/heads/master(r) would be updated by a fast-forward merge in the remote repo.


text:
Q: Terminology of different number representations Background:
I am writing an article and trying to find the proper words/terms for different representations of numbers. The article is regarding calculating the SIN, COS and TAN of a number of angles without getting decimal numbers because the "other" form is better for calculations when these are used in other formulas.
Here are two examples:
Two square roots of two can be written in the following two ways:
First:
$$
2\sqrt 2
$$
Second (floating point/decimal):
$$
2.82842712475
$$
Question
The second example is a decimal number.
What is the name for the representation of two square root of two in the first example?
Thanks!

A: When we write $2\sqrt{2}$ it's simply referred to the exact form.

A: In the case of the values of trigonometric functions that can be expressed symbolically, what you have is an algebraic expression (also called radical), which is a special case of a closed-form expression.
https://en.wikipedia.org/wiki/Closed-form_expression#Comparison_of_different_classes_of_expressions


text:
Q: CSS: Sidebar with folded header ribbon Now I've see various ways to accomplish this effect:

I used to accomplish this with a table, but I've since decided not to use tables like that. What's the best way to do this? Keeping in mind that there's a right border...

A: using 2 block's?
one for the big green and one beneath for the folded corner
you could position it so it overlaps everything so it wont get in a way for whatever block
you might have beneath that contains text and what not

A:

Title

take your two elements, float them left abutted to each other. set a repeating background of the ribbon without the end in div 1.
set a non-repeating background of the ribbon "end" in the other div

A: Here is a pure css solution. I think this could be done more elegantly (using css after and before). Just putting this out there to get you started.
http://jsbin.com/oduju3/edit
Enjoy.


text:
Q: How to get a row and its column from a table with Protractor

                row1Col1
                row1Col2
                row1Col3

                row2Col1
                row3Col2
                row4Col3

                row3Col1
                row3Col2
                row3Col3

var grid = element.all(by.css('.k-grid-content tr')); //this will return row1,row2,row3

but I am unable to use code below to get each row and its column.
grid.each.each(function(row){
    var rowElems = row.findElements(by.tagName('td'));
    expect(rowElems.get(0).getText()).toMatch('/Col1/');
});

the following error message is displaying.
 Message:
     TypeError: Object [object Object] has no method 'findElements'

A: Your grid setup is ok, but for the sake of a shortcut:
var grid = $$('.k-grid-content tr');

Regarding your question, avoid findElements and use chaining element or in this case all Protractor feature. But I'll use $$ shortcut again:
grid.each(function(row) {
  var rowElems = row.$$('td');
  expect(rowElems.count()).toBe(3);
  expect(rowElems.get(0).getText()).toMatch('/Col1$/');
});


text:
Q: How can I call aliases that modify my current shell environment from within a python script? I would like to load a module from within a python script. I am using a custom manager called spack which has a spack load <module> functionality that is similar to the regular module load command on linux. I have tried using both os and subprocessing to run these commands, but the result is always that nothing happens, even though I do not get an error message.
Issuing
spack load mpi

makes the module appear in the list resulting from
spack find --loaded

However, calling these commands in python causes nothing to happen at all:
out = os.popen('spack load mpi').read()
out, err = subprocess.Popen(['spack load mpi'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
out, err = subprocess.Popen(['spack', 'load', 'mpi'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)

Is there something else I can try? Why does this command only work when I type it directly into my shell session? How can I make this load command apply to the particular shell session I am using at the time to call this python script?


text:
Q: Need Sed or any script to remove whitespace between characters and replace with underscores I have an large language .ini file whose lines look like this:
CC MY APPS=My aplications
CC MY APPLICATION SETTINGS TITLE=My Settings

I need to remove all whitespaces between CC and = and replace with underscores like this:
CC_MY_APPS=My aplications
CC_APPLICATION_SETTINGS_TITLE=My Settings

A: It is better to use awk
$ awk 'BEGIN{OFS=FS="="}{gsub(/ /,"_",$1)}1' file
CC_MY_APPS=My aplications
CC_MY_APPLICATION_SETTINGS_TITLE=My Settings

Alternatively if you have Ruby(1.9+)
$ ruby -F"=" -ane '$F[0].gsub!(/\s+/,"_");puts $F.join("=")' file

A: A perl way to do it, very similar to kurumi's solution in Ruby :
perl -i.orig -F= -ane '$F[0]=~s/\s+/_/g;print join"=",@F' file.ini

The original file will be saved into file.ini.orig

A: Alternatively, if your values don't contain a '=', you could try:
perl -pi.bak -e 's/\s+(?=.*=)/_/g' file.ini

using a look-ahead.


text:
Q: Updating a JAR file gives error I have a JAR file and I want to update a .class file inside that jar.
I have the .jar file and the .class file in the same directory (let's say C:/jarupd/)
I'm using Windows Command Prompt and I type:
jar uf myjar.jar dir1/dir2/dir3/.../file.class

It then gives me this error: "No such file or directory"


text:
Q: Allow users to add images and write code snippets in their posts in my CRUD web app like Stack Overflow, Medium I have built my first CRUD web app thanks to Corey Schafer's Flask tutorial on YouTube. Been adding new features.
Currently, a user is able to create a new post that has two input entry fields - Title and Content (please see ). I'd like to add a feature for the users to add images and write code snippets in their posts like we can do here and on Medium. I can't seem to find any resources online on how to get started with this feature. Any help will be greatly appreciated! Thank you.
Tech Stack

*

*Backend - Flask.

*Front End - HTML, CSS, Bootstrap and JS.

*Database - SQLAlchemy.


text:
Q: Popup window shows after kernel closed when using J/Link A popup window always show after kernelLink.close(); And this only happen after expression evaluated as graph. Such as evaluateToTypeset

I got the suggestion from JLinkUserGuide in 'Graphics and Typeset Output' chapter bellowed:

It is very important to note that you execute CloseFrontEnd[] before
  closing the link to the kernel. This is essential to prevent the front
  end from quitting in circumstances where it should not~specifically,
  if an already-running copy was used and the user has open documents.

But this does not work.
This's my code of init KernelLink
System.setProperty("com.wolfram.jlink.libdir", "/usr/local/Wolfram/Mathematica/10.0/SystemFiles/Links/JLink/SystemFiles/Libraries/Linux-x86-64");
KernelLink kernelLink = MathLinkFactory.createKernelLink("-linkmode launch -linkname /usr/local/Wolfram/Mathematica/10.0/Executables/MathKernel -mathlink");
        kernelLink.connect();
        kernelLink.discardAnswer();

Close KernelLink
kernelLink.evaluateToOutputForm("CloseFrontEnd[]", 0);
        kernelLink.close();


text:
Q: What tense do we use with "Thought" I thought you were one of those people who like listening to this kind of music.
I thought you were one of those people who liked listening to this kind of music.
Are both the sentences grammatically correct, and do they mean the same thing?


text:
Q: Issue on SVG group translation with d3.js I am trying to drag a svg group (I am using D3.js)
According to the code, I thought that should be working, but the element movement seems to be "dragging" (move slower than the mouse mouvement). Actually, the shape is make kind of 2 points forward for 1 point backward.
Here is the code
"this.parentNode" is a svg group already translated. I use this translation coord as a starting point for the new translation
function dragged() {
let initX = d3.transform(this.parentNode.getAttribute("transform")).translate[0]
let initY = d3.transform(this.parentNode.getAttribute("transform")).translate[1]

console.log(initX)

console.log(d3.event.dx)

console.log(initX + d3.event.dx)

d3.select(this.parentNode).attr("transform", "translate(" + (initX + d3.event.dx) + "," + (initY + d3.event.dy) + ")");

}

A: I got it working. I finally used d3.event.x instead of d3.event.dx
d3.select(this.parentNode).attr("transform", "translate(" + (initX + d3.event.x) + "," + (initY + d3.event.y) + ")");

I don't really understand why is this x more accurate than this dx but now it works flawlessly.
Edit :
Using d3.event.x is not good, because in a <g> tag, children elements are positioned using x and y coordinates. This creates some issues while dragging.
I am finally using d3.event.sourceEvent.movementX


text:
Q: Is MongoMapper 0.11 compatible with MongoDB 2.2.2? Suggest other Rails libraries for MongoDB? MongoMapper has not been updated since Jan 25, 2012 according to its website.
MongoDB released 2.2.2 on Nov 27, 2012.
Does anyone know if MongoMapper is compatible with the newest release of MongoDB?
If it's not, are there more actively maintained libraries?
We want to make all writes safe by default.

A: MongoMapper may not have had a recent release, but they have been updating the master branch and staying current with new features in MongoDB and in particular Ruby driver for MongoDB.
For example, in this commit into master you can see updates made to make use of the most recent driver (1.8) and its support for "safe" writes as the default, and to replace the now deprecated Mongo::Connection in favor of the new preferred Mongo::MongoClient class.


text:
Q: OpenSSL::SSL::SSLContext SNI servername_cb Not Working As referenced in OpenSSL::X509::Certificate Showing Certificate for Wrong Domain, I need to use TLSv1 or above and Server Name Indication extension.
Even with ssl_version and servername_cb set via the SSLContext, I'm still getting the wrong certificate for myproair.com.
  begin
    timeout(1) do
      tcp_client = TCPSocket.new("#{instance["domain"]}", 443)
      ssl_context = OpenSSL::SSL::SSLContext.new()
      ssl_context.ssl_version = :TLSv1
      ssl_context.servername_cb = "https://#{instance["domain"]}"
      ssl_client = OpenSSL::SSL::SSLSocket.new(tcp_client, ssl_context)
      ssl_client.connect
      cert = OpenSSL::X509::Certificate.new(ssl_client.peer_cert)
      ssl_client.sysclose
      tcp_client.close
      #http://ruby-doc.org/stdlib-2.0/libdoc/openssl/rdoc/OpenSSL/X509/Certificate.html
      date = Date.parse((cert.not_after).to_s)
      row.push("#{date.strftime('%F')} #{cert.signature_algorithm} #{cert.subject.to_a.select{|name, _, _| name == 'CN' }.first[1]}".downcase.ljust(57))
    end
  rescue SocketError
    row.push("down".ljust(57))
  rescue Errno::ECONNREFUSED
    row.push("connection refused".ljust(57))
  rescue Errno::ECONNRESET
    row.push("connection reset".ljust(57))
  rescue Timeout::Error
    row.push("no 443 listener".ljust(57))
  rescue OpenSSL::SSL::SSLError
    row.push("bad certificate - ssl error".ljust(57))
  rescue Exception => ex
    row.push("error: #{ex.class} #{ex.message}".ljust(57))
  end

How do I set the server name in Ruby 2.0 on OS X?

$ ruby --version
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14]

$ openssl version
OpenSSL 0.9.8zc 15 Oct 2014

A: Naturally you use the undocumented 'hostname' method for OpenSSL::SSLSocket!
tcp_client = TCPSocket.new("#{instance["domain"]}", 443)
ssl_context = OpenSSL::SSL::SSLContext.new()
ssl_context.ssl_version = :TLSv1
ssl_client = OpenSSL::SSL::SSLSocket.new(tcp_client, ssl_context)
ssl_client.hostname = instance["domain"]
ssl_client.connect
cert = OpenSSL::X509::Certificate.new(ssl_client.peer_cert)
ssl_client.sysclose
tcp_client.close

I discovered that here while writing code with a similar goal.


text:
Q: Latest Rally release - portfolio attributes not able to be queried I have a custom application that uses the Cardboard object to display portfolio items. We had been using a custom attribute for Kanban state but in the latest release Rally added a standard attribute of a Portfolio Item called "State" which was basically doing what our custom attribute did. The problem is while the Cardboard object will take this attribute as the parameter to build the columns on it will never display any data. The columns all appear empty. I noticed this attribute is different then previous simple drop lists as it has two different options "Theme" and "Feature". Perhaps this works differently and Cardboard doesn't query correctly when passed this type of drop down??? Here is the simple version of the call:
        var dropdownAttribute = "State";
    if (stateDropdown !== null) {
        dropdownAttribute = stateDropdown.getValue();
    }
    var cardboardConfig = {
         types: ["PortfolioItem", "HierarchicalRequirement", "Feature"],
         attribute: dropdownAttribute,
         fetch:"Name,FormattedID,Owner,ObjectID,ClassofService",
         query : fullQuery,
         cardRenderer: PriorityCardRenderer
    };

    if (cardboard) {
        cardboard.destroy();
    }
    cardboard = new rally.sdk.ui.CardBoard(cardboardConfig, rallyDataSource);
    cardboard.display(dojo.body());

A: The new State field is actually a reference to a new Domain Object. We added the object so that we could give each type of Type of Portfolio Item different Kanban States.
What you are seeing is the complete list of all States for all types of Portfolio Item (Theme Feature).
If you want to recreate your current App you would need a new custom field on Portfolio Item and Hierarchical Requirement that has a name other than State. At this time Hierarchical Requirement does have a reference to the new State object but that is something we have plans to explore in the future.


text:
Q: How to get an element from Controller? I need to run 'legacy code' from inside of Controller and need to get element
 function EmailformController($scope) {
     // here I need to get current dom/jqueried element, how to do it?
 }

A: You will want to use a directive. You should never be dealing with DOM elements inside of a controller. Only your business logic should go into the controller, DOM manipulation should go in a directive.


text:
Q: Angular get current focused element in angular I have a website I am trying to do something like this, when I click on 1, I want the background of this element to change to white and when I click on the second one the background of the first one will disappear and pass to the next one...I have been trying to do this for a long time help me I don't know how to do it

1

2

3

A: When we need make "something" exclusive we use one unique variable
selectedIndex:number=-1

If you want not unselected

    1

    2

    3

If you want unselected

    1

    2

    3

NOTE: I use [class.selected], so we use a .css
.selected{
   background:red;
}

You can use style.background or style.background-color using (condition)?value:null, e.g., for the first div
[style.background]="selectedIndex==0?'red':null

A: Like @Kwright02's comment you can do it with css:
.myclass:focus {
  background-color: green;
}

But important: The element must be focusable. So a div isn't, a button is as example.
Second way (add a click handler and change the background directly):
// HTML

test

// Code
onClick(event: any) {
    event.target.style["background-color"] = "green";
  }

Note: This is not the way to go in Angular. Here use property binding and bind a style to a condition as example.
Instead of add a click listener to each control you can use Angular's HostListener like this:
 @HostListener("document:click", ["$event"])
  onAllClick(event: any) {
    event.target.style["background-color"] = "green";
  }


text:
Q: pandas: tricking left join in python please how should i do to get the result below. if the cod of df_1 exists in df_2 then i should add the row as explained in my code below.
data1 = {'date': ['2021-06', '2021-06', '2021-07', '2021-07', '2021-07', '2021-07'], 'cod': ['12', '12', '14', '15', '15', '18'], 'Zone': ['LA', 'NY', 'LA', 'NY', 'PARIS', 'PARIS'], 'Revenue_Radio': [10, 20, 30, 50, 40, 10]}

df_1 = pd.DataFrame(data1)

data2 = {'date': ['2021-06', '2021-06', '2021-07', '2021-07', '2021-08'], 'cod': ['12', '14', '15', '15', '18'], 'Zone': ['PARIS', 'NY', 'LA', 'NY', 'NY'], 'Revenue_Str': [10, 20, 30, 50, 5]}

df_2 = pd.DataFrame(data2)

the expected output is
data_result = {'date': ['2021-06', '2021-06', '2021-06', '2021-07', '2021-07', '2021-07', '2021-07', '2021-07','2021-07'], 'cod': ['12', '12', '12', '14', '14', '15', '15', '15', '18'], 'Zone': ['LA', 'NY', 'PARIS','LA', 'NY', 'NY', 'PARIS', 'LA', 'PARIS'], 'Revenue_Radio': [10, 20, 0,  30, 0, 50, 40, 0, 10], 'Revenue_Str': [0, 0, 10,0, 20, 50, 0, 30, 0]}
df_result = pd.DataFrame(data_result)

A: Use inner join by date and cod first, and then outer join with replace missing values:
df22 = df_2.merge(df_1[['date','cod']].drop_duplicates(), on=['date','cod'])
df = (df_1.merge(df22, on=['date','cod','Zone'], how='outer')
          .fillna(0)
          .sort_values(['date','cod'], ignore_index=True))
print (df)
      date cod   Zone  Revenue_Radio  Revenue_Str
0  2021-06  12     LA           10.0          0.0
1  2021-06  12     NY           20.0          0.0
2  2021-06  12  PARIS            0.0         10.0
3  2021-07  14     LA           30.0          0.0
4  2021-07  15     NY           50.0         50.0
5  2021-07  15  PARIS           40.0          0.0
6  2021-07  15     LA            0.0         30.0


text:
Q: But how to use this to show that $ \ \int_5^{\infty} e^{-x^2} dx \ $ is negligible as compared to $ \int_5^{\infty} e^{-5x} dx \ $? Calculate the integral $ \ \int_5^{\infty} e^{-5x}dx \ $ and use this to show that $ \ \int_5^{\infty} e^{-x^2} dx \ $ is negligible.
Answer:
$ \ \int_5^{\infty} e^{-5x}dx =[\frac{e^{-5x}}{-5}]_5^{\infty}=\frac{e^{-25}}{5} $
But how to use this to show that $ \  \int_5^{\infty} e^{-x^2} dx \ $ is negligible as compared to $ \int_5^{\infty} e^{-5x} dx \ $ ?

A: Note that for $x>5$ we have $$ e^{-x^2} < e^{-5x}$$
 Thus $$ \int _5^{\infty} e^{-x^2} dx \le \int_5^{\infty} e^{-5x} dx = \frac {e^{-25}}{5} \approx 0$$

A: Let
$I(a)
=\int_a^{\infty} e^{-ax}dx
$
and
$J(a)
=\int_a^{\infty} e^{-x^2}dx
$.
I will show that
$\dfrac12(1-\dfrac{1}{2a^2+1})
\lt \dfrac{J(a)}{I(a)}
\lt \dfrac12
$.
$I(a)
=\int_a^{\infty} e^{-ax}dx
=\dfrac{e^{-ax}}{-a}|_a^{\infty}
=\dfrac{e^{-a^2}}{a}
$.
Since
$(e^{-x^2})'
=-2xe^{-x^2}
$,
$-\dfrac1{2x}(e^{-x^2})'
=e^{-x^2}
$,
so
$(\dfrac1{2x}e^{-x^2})'
=\dfrac1{2x}(e^{-x^2})'-\dfrac1{2x^2}e^{-x^2}
=-e^{-x^2}-\dfrac1{2x^2}e^{-x^2}
$
so
$\int e^{-x^2}dx
=-\dfrac1{2x}e^{-x^2}-\int \dfrac1{2x^2}e^{-x^2}dx
$
so
$\begin{array}\\
J(a)
&=\int_a^{\infty} e^{-x^2}dx\\
&=-\dfrac1{2x}e^{-x^2}|_a^{\infty}-\int_a^{\infty} \dfrac1{2x^2}e^{-x^2}dx\\
&=\dfrac1{2}I(a)-\int_a^{\infty} \dfrac1{2x^2}e^{-x^2}dx\\
\end{array}
$
Therefore
$J(a) < \frac12 I(a)
$
or
$\dfrac{J(a)}{I(a)}
\lt \dfrac12$.
Since
$\int_a^{\infty} \dfrac1{2x^2}e^{-x^2}dx
\lt \int_a^{\infty} \dfrac1{2a^2}e^{-x^2}dx
=\dfrac1{2a^2}\int_a^{\infty} e^{-x^2}dx
=\dfrac1{2a^2}J(a)
$,
$\begin{array}\\
J(a)
&=\dfrac1{2}I(a)-\int_a^{\infty} \dfrac1{2x^2}e^{-x^2}dx\\
&\gt\dfrac1{2}I(a)-\dfrac1{2a^2}J(a)\\
\end{array}
$
so
$\frac12 I(a)
\lt J(a)(1+\frac1{2a^2})
= J(a)\dfrac{2a^2+1}{2a^2}
$
or
$\dfrac{J(a)}{I(a)}
\gt \dfrac12\dfrac{2a^2}{2a^2+1}
= \dfrac12(1-\dfrac{1}{2a^2+1})
$.

A: By letting $I_1=\int_{5}^{+\infty}e^{-x^2}\,dx$ and $I_2=\int_{5}^{+\infty}e^{-5x}\,dx$ we have
$$ e^{25} I_1 = \int_{0}^{+\infty} e^{-x^2-10x}\,dx,\qquad e^{25}I_2=\int_{0}^{+\infty}e^{-5x}\,dx=\frac{1}{5} $$
and by just exploiting $e^{-x^2}\leq 1$ we get $e^{25}I_1\leq\frac{1}{10}$, such that $I_1\leq \frac{1}{2}I_2$.
On the other hand the ratio $\frac{I_1}{I_2}$ is not really negligible. We have
$$ \int_{0}^{+\infty}(1-e^{-x^2})e^{-10 x}\,dx \leq \int_{0}^{+\infty}x^2 e^{-10 x}\,dx=\frac{2}{1000}$$
hence
$$ \boxed{\frac{1}{2}-\frac{1}{100}\leq\frac{I_1}{I_2}\leq \frac{1}{2}.}$$

A: Observe that $0\leq e^{-x^2}<e^{-5x}$ for most positive $x$ values. You can use FTC to find $\int_5^{\infty} e^{-5x}dx$, but not the other integral.


text:
Q: Search Form Not searching Ive got a knowledgebase and a bunch of test articles setup, when i use the search function nothing actually searches in the search bar after i search http://Example.com/Knowledge.html?s=Search+Test#
and it just doesn't search the page doesn't go no where
here is the code i think it might be!

Have a Question?

If you have any question you can ask below or enter what you are looking for!

        <form id="search-form" class="search-form clearfix" method="get" action="#" autocomplete="off">
            <input class="search-term required" type="text" id="s" name="s" placeholder="Type your search terms here" title="* Please enter a search term!" />
            <input class="search-btn" type="submit" value="Search" />

        </form>

if its not that! i can send the hole HTML file.

A: I don't think that you should have action="#" it it possible that you grabbed this from an example and forgot to change a couple of things. That should equal whatever script is actually doing the searching.


text:
Q: Weird char (�) appears after doing html_entity_decode In a separate YML file i have :
flags:       [<img src="/images/cms_bo/icons/english.png" alt="English"/>]
When i call this into my code, it's not interpreted, so i used html_entity_decode.
It works but i have only 1 strange char just before my image : �
<?php echo html_entity_decode($form['lang']->render()); ?>

All my files are UTF8 encoded. Do you have an idea on what i've missed to solve this problem ?
PS:
      public static function getI18nCulturesForChoice()
  {
      return array_combine(self::getI18nCultures(), self::getI18nCulturesFlags());
  }

A: Try using html_entity_decode($form['lang']->render(),ENT_QUOTES, "UTF-8");

A: Prior to PHP 5.3.3, the default character set for html_entity_decode was ISO-8859-1!  If you're working with UTF-8, you will need to use the third argument to the function to tell it to deal with UTF-8 instead of assuming ISO-8859-1.
This is blindly assuming you're using an older version of PHP.
If you are using a newer version of PHP, consider using iconv with the //IGNORE//TRANSLIT flags to try and remove any bad UTF-8 sequences before passing the string into html_entity_decode.

A: Maybe your file has a Byte Order Mark (BOM) set.


text:
Q: How to Increase Disk Space GitLab Runner I have GitLab runner running on AWS and I've connected it to my GitLab Project. During on CI/CD Pipeline I want to run End to End test on my React Native mobile using reactnativecommunity/react-native-android image. But when want to create SDK the job fail and display error No space left on device. However when I run df -h on .gitlab-ci.yml script display disk overlay only 16G. On GitLab Runner config i use amazonec2-instance-type=c5d.large who has 50GB storage disk. My question is how to increase the storage space disk on GitLab runner pipeline more than 16G. Here the output on running df -h:

Filesystem
Size
Used
Avail
Use%
Mounted on

overlay
16G
14G
2.2G
86%
/

tmpfs
64M
0
64M
0%
/dev

tmpfs
1.9G
0
1.9G
0%
/sys/fs/cgroup

/dev/nvme0n1p1
16G
14G
2.2G
86%
/builds

shm
64M
0
64M
0%
/dev/shm

A: The AWS Documentation has it documented here
This question was also answered here


text:
Q: How do I search if a specific file name exists on the root of every drive? I want to know what to do so that my program can find a specific file on every drive. I would like the program to search only the root of the drive and block it from accessing the subfolders of the root so that the program will not do unnecessary access.
My actual goal is, when the filename which exists on the root of one of the drives matches what I specify in my code, it can execute my commands on that directory.


text:
Q: why Break Apart Remove my test in flash cs6? I want to convert text to shape in flash cs6 AS3
when I click Break Apart then my text is removing.
Please advice me why?

A: I think you better enter your text in another software, like word or paint
Capture the screen (using PrtScr or PrintScreen or an utility)
Paste in your stage
Convert to symbol
Enter the symbol and then Break Apart!!
It will then be an Image and you can change it as you like!!
Good Luck!


text:
Q: What would Shazam's wand have done with Sivana? In Shazam (2019) if Sivana's plan had succeeded and he had gotten

 Billy to hold the wand of power and Sivana said "Shazam"

What would have happened?

 A) would Billy have lost the Shazam power as it transferred to Sivana (just as it had transferred from the wizard to Billy)

Or

  B) or would Sivana be an additional Shazam and Billy would have kept his powers (just like it did with the siblings later on)

?


text:
Q: Adding threading and email subscriptions to comments I've built a simple rails app with three models, Posts, Users, and Comments.
I've tried every commenting gem out there and they all have some shortfall.
So I build my own comments system.
Users can comment on Posts. Every comment is votable (using acts_as_votable gem). A users score is made up by the sum total votes they have received on their comments.
Here is what I have in my schema for the comments:
 create_table "comments", force: true do |t|
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
    t.integer  "post_id"
  end

In my user model:
class User < ActiveRecord::Base
  has_many :comments
  acts_as_voter
end

In my post model:
class Post < ActiveRecord::Base
  has_many :comments
end

In my comment model:
class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  acts_as_votable
end

In my comments controller:
class CommentsController < ApplicationController
  def create
    post.comments.create(new_comment_params) do |comment|
      comment.user = current_user
    end
    respond_to do |format|
    format.html {redirect_to post_path(post)}
    end
  end

  def upvote
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.liked_by current_user

  respond_to do |format|
        format.html {redirect_to @post}
    end
end

  private

  def new_comment_params
    params.require(:comment).permit(:body)
  end

  def post
    @post = Post.find(params[:post_id])
  end

end

In my routes file:
resources :posts do
    resources :comments do
    member do
      put "like", to: "comments#upvote"
    end
  end
  end

In my view:
<% @post.comments.each do |comment| %>
  <%= comment.body  %>

  <% if user_signed_in? && (current_user != comment.user) && !(current_user.voted_for? comment) %>

<%= link_to "up vote", like_post_comment_path(@post, comment), method: :put %>

<%= comment.votes.size %>

<% else %>

<%= comment.votes.size  %>

<% end %>
<% end %>

<%= form_for([@post, @post.comments.build]) do |f| %>

<%= f.text_area :body, :cols => "80", :rows => "10" %>

<%= f.submit "comment" %>

<% end %>

In the user profile views: (this shows the users score
<%= (@user.comments.map{|c| c.votes.count}.inject(:+))%>

How do I implement threading?(at one level, I'm assuming multiple levels just makes it really messy)
How do I make the threaded comments votable?(both the parents and children) What has to be done with the routes?
How do I ad a simple email notification a user can subscribe to to receive a simple message saying that a new comment has been posted to their thread?
How do I pull the users score calculated by all votes received on comments made by the user including child comments?

A: If I understand the question correctly, you want to allow comments to be commented on.  In that case, in your Comment model you will need a parent_id:integer attribute. Then add the following associations :
class Comment
    ...
    belongs_to :parent, class_name: 'Comment'
    has_many :children, class_name: 'Comment', foreign_key: 'parent_id'
    ...
end

Now you have a tree structure for your comments. This allows comments of comments of comments and so on.
if my_comment.parent.nil? then you are at the root.  if my_comment.children.empty? then there are no comments on the comment.
Trees can be expensive to move through, so adding a max depth could be smart.

A: How do you implement threading? (To answer one of your questions)
Make the comment-to-user association polymorphic, and then you can add a comment-to-comment association the same way.
What was the 'shortfall' you found with existing gems that prevented you doing this? (Since acts_as_commentable supports this out if the box)


text:
Q: How to correctly implement .sql file in MS SQL docker-compose.yml file? I have a problem implementing docker-compose.yml file for MS SQL Database container in Docker.
I tried to set up "setup.sql" file within "volumes:" parameter but it did not worked out for me. Maybe wrong path? How to correctly set up empty database using ready .sql file stored on local host computer?
Here is the code without volumes parameter:
version: "3.7"
services:
  sql-server-db:
    container_name: sql-server-db
    image: mcr.microsoft.com/mssql/server:2019-latest
    ports:
      - "1433:1433"
    environment:
        SA_PASSWORD: "secret123new!"
        ACCEPT_EULA: "Y"


text:
Q: Not able to drop field in MariaDB/MySql table with FOREIGN KEY I tried to apply the workaround described in a similar question with no success.
In my scenario there are two related tables; I wish to drop the ean_code field from table product.

CREATE TABLE `brand` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(512) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `product` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `ean_code` varchar(255) DEFAULT NULL,
  `brand_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_eancode_unique` (`brand_id`,`ean_code`),
  CONSTRAINT `fk_product_brand_id` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

As explained by @bill-karwin the plain drop column fails:
> ALTER TABLE product drop column `ean_code`;
  Key column 'ean_code' doesn't exist in table

So I tried the suggested workaround "drop both the unique index and the field in the same statement":
> ALTER TABLE `product` DROP KEY `product_eancode_unique`, DROP COLUMN  `ean_code`;
  Cannot drop index 'product_eancode_unique': needed in a foreign key constraint

The error reported is quite peculiar in my opinion since the given field is NOT involved in any relation between the two tables;
I experimented the db<>fiddle with all available mariadb and mysql versions with no joy.
PS I've isolated the culprit constraint by trial and error using db-fiddle but ant db instance will do the job (apart from experimenting with different db versions).

A: The workaround I've found myself is "drop the constraint before dropping index and field, then recreate the constraint".
alter table `product` drop constraint `fk_product_brand_id`;
alter table `product` drop key `product_eancode_unique`, drop column `ean_code`;
alter table `product` add foreign key `fk_product_brand_id`(`brand_id`) REFERENCES `brand`(`id`)

As in this db-fiddle.
Still I do not know how to quickly isolate the constraint causing all this.

A: You cannot drop the column because the foreign key constraint uses this index. You must create an index which will be used for constraint checking firstly and drop index which includes the column to be dropped. Then the column may be dropped.
ALTER TABLE product ADD INDEX (brand_id),
                    DROP INDEX product_eancode_unique,
                    DROP COLUMN `ean_code`;

https://dbfiddle.uk/?rdbms=mariadb_10.5&fiddle=f36688300eeff3af867872b0227981ac


text:
Q: Launching from .bat not working the same as running .ps1 directly I'm trying to make a script that people can doubleclick to run a set of commands that changes occasionally. In linux I run a .sh that wgets another sh (that I can change when needed) and runs it. I'm looking for a similar solution for Windows.
I looked into PowerShell but found out it needs to be run from a .bat to allow double clicking, so now I have the following:
foo.bat file:
@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%bar.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

that calls bar.ps1:
Invoke-WebRequest https://dl.dropboxusercontent.com/u/xxx/bar2.ps1 -OutFile bar2.ps1

Running bar.ps1 from PowerShell works fine and downloads bar2.ps1, but running the batch file does not, or at least not to the directory both files are in (can't find it anywhere, though I guess it might be a working directory problem still?).

A: Your batch file is running the PowerShell script with elevated privileges. Doing this changes the working directory to C:\Windows\system32 (for security reasons), so you'll most likely find the downloaded file there. To get the ouptut file in the same directory as the script you could change the PowerShell script like this:
$dir = Split-Path $MyInvocation.MyCommand.Path -Parent
$filename = 'bar2.ps1'
$url = "https://dl.dropboxusercontent.com/u/xxx/$filename"

Invoke-WebRequest $url -OutFile "$dir/$filename"

With that said, why are you running a download script with elevated permissions in the first place? Don't do that.


text:
Q: Using the Id of td how to fing id of corresponding tr? i have id of td and i want to get the id of parent tr? i have following code
 $(".isActive").click(function() {
   var checkBox_id = $(this).attr("id");          // id of checkbox inside td//
   var $this = $('#' + checkBox);
   var column_id = $this.parent().attr('id');     // id of td//
   var row_id =   ???                              // get id or tr using above td
 });

A: There's no need to follow a chain of IDs - jQuery can find the closest enclosing table row for you:
$(".isActive").click(function() {
   var row_id = $(this).closest('tr').attr('id');
});

A: var column_id = $this.parent().parent().attr('id') //id of tr

A: You could use this i think
var row_id =   $this.closest('tr').attr('id')

A: Couple ways of doing it:
var row_id = $this.parent().parent().attr('id');
var row_id = $('#' + column_id).parent().attr('id');

A: i think you are missing a point here:
var checkBox_id = $(this).attr("id");
var $this = $('#' + checkBox);

The second line is is completly unnecessary. $this will refer to the same element as $(this). You just can do:
var $this = $(this);

for the same effect.
If you need the id of the tdand tr for the same thing, then you don't need it either.
var $td = $this.parent(); // Reference to td
var $tr = $td.parent(); // Reference to tr


text:
Q: Root User Can't run Files Off Desktop or Documents? Mojave 10.14.3 Anybody else have this issue with root in Mojave (10.14.3)? I have root enabled and I try to run a simple .txt/.png/.pkg off the root desktop. It doesn't run, I get an error in Console "Unable to load Info.plist eGPU Overrides." and Finder crashes.
I have the same file in the Downloads Folder and try to open it and it runs just fine. I thought this had to do with TCC so I added Finder and TextEdit into the Full Disk Access inside System Preferences > Security & Privacy > Privacy > Full Disk Access. Nothing, still same bug.
All my permissions seem to be set correctly for the root's directories and the files. This happened right after I upgraded to Mojave. I also tested this with a clean Mojave install. Same issue.
TLDR - Mojave 10.14.3 - Root Desktop - can't open a file, Root Downloads Folder, yes I can open same said file?
Here is a gif: https://imgur.com/a/aSG15KH


text:
Q: Ansible playbook exiting without giving proper error message I'm facing an issue with an Ansible playbook. Ansible is exiting without giving any proper error message. Here is my code:
- name: Installing dependencies
  yum: pkg={{ item }} state=latest
  with_items:
      - gtk+-devel
      - gtk2-devel

I wanted to install above packages in my CentOS7. I'm able to install it manually by giving the command sudo yum install gtk+-devel gtk2-devel. But Ansible is throwing the below message and exiting from execution:
TASK [server : Installing dependencies] ****************************
ok: [localhost] => (item=[u'gtk+-devel', u'gtk2-devel'])

NO MORE HOSTS LEFT *************************************************************
    to retry, use: --limit @/Users/rolindroy/ansible/setup.retry

PLAY RECAP *********************************************************************
localhost            : ok=2    changed=1    unreachable=0    failed=1

Ansible version: 2.1.2.0
EDIT:
Running the playbook with the -vvv option yields this error (but I'm able to install it manually):
failed: [localhost] (item=[u'gtk+-devel', u'gtk2-devel']) => {"changed": false, "failed": true, "invocation": {"module_args": {"conf_file": null, "disable_gpg_check": false, "disablerepo": null, "enablerepo": null, "exclude": null, "install_repoquery": true, "list": null, "name": ["gtk+-devel", "gtk2-devel"], "state": "latest", "update_cache": false, "validate_certs": true}, "module_name": "yum"}, "item": ["gtk+-devel", "gtk2-devel"], "msg": "No Package matching 'gtk+-devel' found available, installed or updated", "rc": 0, "results": []}


text:
Q: How to set the data type as a model in strong loop remote method definition I whant to set the data type of my remote method as a model. If I'm in User.js I can do this:
User.remoteMethod('contacts',  {
    accepts: [
        {
            arg: 'contacts',
            type: User,
        }
    ],
    returns: {arg: 'data', type: 'json'}
});

but I have another model named Contac and I want to replace "type: User" with "type: Contact".
But on this context, I think that the app object can't be access so if there is any way to do this?

A: To access app object in model.js,
ModelName.getApp(function(err, app) {
    if(err) throw err;

    //use app object here. for eg.
    //app.models.Contact.find({}, function(err, contacts) {
    //    if(err) throw err;
    //    console.log(contacts);
    //});
});

This way you can get app object and use it to access other models.

A: I think the type that you want is 'object' which can be everything as a object.
It depends on your really input. If you want POST the whole user or contact as a json data, 'object' is recommended, or if you just want input a foreignKey like "contactId" to indicate a contact, an id is adequate because you can get the instance in your logic code of the remote method like:
User.contact = function (contactId, cb){
  Contact = User.app.models.Contact // suppose Contact is the so-called another model
  Contact.findById(contactId,function(err,instance){
    ...
  cb(null, JSON.stringify(instance); //instance is the contact whose id is contactId
  });
}


text:
Q: Cross-copying DATE atributes of a file in PowerShell Usecase:
There are ~4000 files that have lost any relation to the date they were created, and as a result the order totally mixed up.
After copying the entire directory to Windows i saw what the problem is: Android doesn't store the creation timestamp of a file, and sorts only by Last Modification time of the file. Whereas the "Modification Time" was the "broken" attribute which caused all my files to get out of their order:

From here i know how to proceed - just copy the "Date" attribute into the "Date Modified" for every single file, and i would do it with the following code:
$picts =  Get-ChildItem -force | Where-Object {! $_.PSIsContainer}
foreach($object in $picts)
{
      $object.LastWriteTime=($object.Date)
}

The problem is that $object.Date is a wrong argument, because Date doesn't seem to represent the "Date" attribute of the file in Powershell.
Does anybody know what is the right ChildItem to represent the "Date" or/and "Date taken" attributes?

A: You can obtain the Date Taken value programatically by loading the picture as an Image and then retrieving the appropriate property:
function Get-DateTaken
{
  param(
    [ValidateNotNull()]
    [System.IO.FileInfo]$File
  )

  # Ensure System.Drawing assembly is available
  Add-Type -AssemblyName System.Drawing

  try{
    # Attempt to load image file from disk
    $img = [System.Drawing.Image]::FromFile($File.FullName)
    try{
      # Get the System.Photo.DateTaken property
      $dateTakenValue = $img.GetPropertyItem(36867).Value

      # Decode to string
      $dtString = [System.Text.Encoding]::UTF8.GetString($dateTakenValue)

      # Parse as DateTime, property string is in the format `yyyy:MM:dd HH:mm:ss\0`
      $dt = [datetime]::Now
      if([datetime]::TryParseExact($dtString.Trim(0), 'yyyy:MM:dd HH:mm:ss', $null, 'None', [ref]$dt)){
        # Success, return DateTime
        return $dt
      }
    }
    catch{
    }
  }
  finally{
    # Clean up
    $img.Dispose()
  }
}

Now that we can translate a FileInfo reference to the corresponding date, we can do:
$picts =  Get-ChildItem -Force | Where-Object {! $_.PSIsContainer}
foreach($object in $picts) {
  if(($DateTaken = Get-DateTaken $object)){
    $object.LastWriteTime = $DateTaken
  }
}

A: I don't have imported pictures from an Android phone so this will be a more general answer to how you can troubleshoot things like this.
If you take an arbitrary file in your collection with Get-ChildItem you can see all the different meta data it has by doing the following:
$test = Get-ChildItem "Yourfile.jpg"
$test.LastWriteTime | Get-Member

This will show you both the type of the object (in this case System.DateTime) and will also give you a list of all methods you can use with it. If you want to understand what the $object.Date is in your example, I would use the same approach and pipe $object.Date to Get-Member to see what type of object it is. If they are different, you would have to convert the $object.Date into a System.DateTime before you can change the modification date of the file.


text:
Q: stale element reference error after self.driver.back()? I'm getting Selenium exception stale element reference: element is not attached to the page document after the first iteration of the for loop. My code is :
  for gc in grpCommune:
         self.driver.execute_script("return arguments[0].scrollIntoView(true);", gc)
         self.driver.execute_script("window.scrollTo(0, 0);")
         e=gc.find_element_by_xpath('//a[2]')
         e.click()
         sleep(1)
         ...
         genertaeCSV()
         self.driver.back()

how can I resolve it?

A: Stale element exception occuring when element in on page but selenium driver instance could not interect with that element.
Following actions can be resolve stale element exception
1.Refresh page by using  "navigate(). refresh()" method in selenium
2.using loop try to click or check visible of that element if that element visible or already clicked exit from loop.

A: Stale Element exception occurs when the selenium reference bound to the element is no more valid, generally, this happens when you either navigate away from the page or refresh the page or the contents on the page is reloaded. In your case, you are trying to refer to the gc element which was captured with a reference before clicking the e element. The moment you clicked on e element using e.click() button, all the references in grpCommune is no longer valid. So, you will be able to run only the first iteration successfully with your code.
How do I fix this code:
Get the gc element within the for loop. Rather than using for each use for loop with the index.


text:
Q: Visual Studio Code: exclude sections of a file from autoformat? I'm dealing with a bunch of legacy C code whose formatting is all over the place and I would like to clean it up as I work. However, there are some sections that I do not want touched (or I'd rather format manually (such as structures being used as bitfields with an explanation as to what each bit represents in comments). I'm working in an embedded environment, so understanding what each bit represents is important and keeping that nicely formatted is important, however, the C-lang formatter in VS Code wants to do its own thing with this kind of stuff.
How can I exclude sections of a file from autoformat?

A: Are you using the clang-format extension clang-format ?  If so, see disable formatting on a piece of code.
int formatted_code;
// clang-format off
    void    unformatted_code  ;
// clang-format on
void formatted_code_again;


text:
Q: Backbone.js Uncaught TypeError: Object [object Array] has no method 'on' Can anyone help me with this one? I don't know what's going wrong.
Getting data from a json file:
this.categoryTrees = new CategoryTrees();
this.categoryTrees.getCategoryTreesFromJSON();

this.categories = new Categories();
this.categories.getCategoriesFromJSON();

Creating views for it:
//view for startscreen
this.startscreenView = new StartscreenView({collection: this.categoryTrees});

//view for subjectsList
this.subjectsListView = new SubjectsListView({collection: this.categories.where({ category_tree : "onderwerpen" }) });

The second one with the where clause gives me an error: Uncaught TypeError: Object [object Array] has no method 'on'
When I don't put up the where clause it works just fine. In console I am able to perform the where function without any problems.
Do I miss something here?

A: The where method will return an array of all the models in a collection that match the passed attributes.  So it doesn't return a Backbone.Collection so you get the on undefined error.
You need to create a new Categories collection from the result of the where with :
this.subjectsListView = new SubjectsListView({
    collection: new Categories(
        this.categories.where({ category_tree : "onderwerpen" }))
});

A: Found a proper solution. Before starting the backbone app I'm retrieving the JSON data in a new function loadDataAndStartApp(). This function is loaded when the dom is ready, and once the JSON is loaded it starts the backbone app. This way you are certain to have all the data available. Together with what nemesv said about creating a new categories function and al the other suggestions at his answer I worked out the following answer to this problem.
var AppRouter = Backbone.Router.extend({
routes: {
    "": "startscreen",
    "Onderwerpen": "subjectsList"
},

initialize: function  (options) {

    this.categories = new Categories( options.categories );

    this.subjectsListView2 = new SubjectsListView({
        collection: new Categories(
            this.categories.where({ parent : null, name : "Evenwicht" })
        )
    });

    //view for spacesList

},

startscreen: function () {
    $('#app').html(this.startscreenView.render().el);
},

subjectsList: function () {
    $('#app').append(this.subjectsListView2.render().el);
},

});

function loadDataAndStartApp(){

var categories     = []

// LOAD APP DATA
$.ajax({

    url      : './catalogue.json',
    dataType : 'json'

}).done(function(data){

    console.log('Catalogue retrieved');

    // GET CATEGORIES
    _.each(data.categories, function( categorieObj ){

        var categorieName       = _.keys(categorieObj)[0],
            categorieAttributes = categorieObj[categorieName];

        categories.push( categorieAttributes );

    });

    // START APP
    var app = new AppRouter({
        categories     : categories
    });

    Backbone.history.start();
});
}

$(function(){
// ON DOM READY

loadDataAndStartApp();
});


text:
Q: JSF View Scope does not shutdown First:
I have two Managed Beans.
Bean A:

*

*@ViewScope

*Contains a lazyloading datatable depending on some session value, initialized in the @PostConstruct

Bean B:

*

*@ViewScope

*Changing the session value which is used in Bean A

I do following;

*

*setting my session data with the JSF site using Bean B

*loading the jsf site which uses Bean A

*setting other session data with Bean B

*loading the jsf which uses Bean A again

The Problem is following:
If I am loading the JSF site with Bean A again, the PostConstruct which is initializing the datatable is not loaded again.
I thought that if I use the view scope, the ManagedBean would be destroyed if I navigate through different JSF sites.
Please help me to understand this Problem. What am I doing wrong?

A: It should yes. The view scope should stay in-tact for as long as you stay on the same view.
There have been many problems with this scope in past versions of JSF however, including relating to PostConstruct; which version are you using right now? It should mention that in the logs during application startup.


text:
Q: How to take user input and change language with i18next-express-middleware? I am new to node.js and I want to internationalize my application. I have started off with the template from i18next-express-middleware github along with i18next website. I want the user to click the button and have the server fetch the .json file and serve the translation back to the user. Below is my code:
HTML

  <button onclick="i18next.changeLanguage('en')">
  english
  </button>
  <button onclick="i18next.changeLanguage('de')">
  german
  </button>

Node.js/Express
const express = require('express');
const i18next = require('i18next');
const i18nextMiddleware = require('i18next-express-middleware');
const Backend = require('i18next-node-fs-backend');

const app = express();
const port = process.env.PORT || 8080;

i18next
  .use(Backend)
  //.use(i18nextMiddleware.LanguageDetector)
  .init({
backend: {
   loadPath: '/translate/i18next-express-middleware-master/examples/basic/locales/{{lng}}/{{ns}}.json',
   addPath: '/translate/i18next-express-middleware-master/examples/basic/locales/{{lng}}/{{ns}}.missing.json'
},
fallbackLng: 'en',
preload: ['en', 'de'],
saveMissing: true
});
app.use(i18nextMiddleware.handle(i18next));

app.get('/', (req, res) => {
  res.send(req.t('home.title'));
});

app.listen(port, (err) => {
  console.log(`Server is listening on port ${port}`);
});

I have looked for documentation on how to communicate with the client's choice for language, but I simply have no idea how you go about it. Am I missing a key component? In the docs, they talk about how to set the language, but never how to use user input and have their choice reflected in the HTML that the user receives. Any guidance would be appreciated.
P.S. I am not married to the i18next express, so if you are aware of a much better method to serve translation to the client via backend, feel free to suggest it/provide proof of concept.

A: using express i expect you to want the translation happening on the serverside. So you need to trigger the change language on the serverside. For that you can use the language detector coming with the i18next-express-middleware: https://github.com/i18next/i18next-express-middleware#language-detection
on client just do a location change setting the language:
<button onclick="function() { window.location = '/?lng=de'; }">
this will reload the page setting lng to de - server will detect that lng and render your template in correct language (using the t helper in your templates).
if you like doing all the translations on clientside just follow the samples on i18next (if doing clientside translations i highly recommend using one of the framework integrations and not doing all the heavy lifting manually by setting innerHTML -> https://www.i18next.com/supported-frameworks.html).


text:
Q: Show corresponding date on recurring reminder slack I want to show the corresponding date on the recurring reminder of slack.
Ex: /remind me "Today is dd/mm/yyyy" at 07:00AM every Tuesday
Now i want to see the current date in the message instead of dd, mm, yyyy on that corresponding day.

A: You can't do that via the remind command since Slack treats it as a message to send to. But you can definitely use the API to do so.
You can make a Cron Job that gets the date and formats it into the dd/mm/yy
or use a simple chat.postMessage


text:
Q: How to get username in PHP using Active Directory without username and password How to determine and store to variable a user name which is connected with Active Directory in PHP?
I read that it's easy to do using Windows authentication on IIS with AUTH_USER variable, but unfortunately the website will be on a Linux server or on XAMPP
And I need to do it without modules, such as mod_auth_kerb and mod_ntlm.
I was thinking of doing this through an LDAP request. Ask for username and password and make ldap_bind or ldap_connect. If the username and password are correct, then our LDAP server responds and we put username in the variable
But I don't like the idea of asking for a user password, because it will be transmitted in plain text?
In our AD, TLS and SSL are not configured, and there is no access to configure them.
Are there any other options?


text:
Q: how the proper way users.users and authorizedKeysFiles in configuration.nix I just learn to install nixos
here is some from my /etc/nixos/configuration.nix
...
  users.users.bino = {
    isNormalUser = true;
    extraGroups = [ "wheel" ]; # Enable 'sudo' for the user.
  };

...

  # Enable the OpenSSH daemon.
  services.openssh.enable = true;
  services.openssh.authorizedKeysFiles = ["./ssh-keys.nix"];

and here is my /etc/nixos/ssh-keys.nix
[root@nixos_bino:/etc/nixos]# cat ./ssh-keys.nix
{
  bino = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCt7LNPLKQdWPB/AdpMaghkyju0aeZ9gFvQcxPWNqKXRpDiQvPTtSf+lCgTx1XR2drEzTjUqeo33ztA+2/t9RNluVr9etGCFYkmjNLyxZ0ohCR+MUxyZvsrYUATPsBZipkxCosTfRlabbgjmLxOwrcutMLgvuaIQRrPKG/zp5oQbiMi0M3F+QbN/R1jrWGNrOa+uPg75/TubpRTjddsi24G2hw75/Z5OJ6JZi//hc3uL85jtMXqOYLlBSBzdLHh+TgaK2RpsHKYrYd9WAs99BGuIBmJ4WEW2yyxpo9+6fPbjD0WwjB9UUSd5olgbGYrGaCfBQAE0ztAR5OzhI944mNV bino@bino-ThinkPad-X201";
}

I run nixos-install got no error
Reboot
Try to ssh that new installation with ssh bino@192.168.1.228 (192.168.1.228 is configured as static IP), the host still ask for password.
Try to ssh with root, got success.
Found that user 'bino' is created including it's home directory.
So my question is : How is the proper way to add some default user with ssh-key in configuration.nix ?
Sincerely
-bino-

A: The problem is with
services.openssh.authorizedKeysFiles = ["./ssh-keys.nix"];

which tells NixOS to use the plain string "./ssh-keys.nix" somewhere int the system configuration.
What you intended is for the file to be read and its contents used in the system configuration.
The following should work:
users.users.bino.openssh.authorizedKeys.keys
 =
  let keys = import ./ssh-keys.nix;
  in [ keys.bino ];


text:
Q: * fit parent
* width I would like my nested
 to fit parent <il id='parent'> width.
HTML:

  $variable

one

two

CSS:
#setter {padding:0 15px; display:inline-block} /*as menu item*/
#child {...?}

The problem is that link is setting the
 width since the link text is changeable variable. With other words,
 width cannot be fixed.

A: You can float the
:
#parent
{
    float: left;
}

http://jsfiddle.net/G3TBn/4/
But then, if the content in #child grows wider than #setter, the width of the
 will grow as well:
http://jsfiddle.net/G3TBn/5/
In that case, you could then position #child absolutely:
#parent
{
    float: left;
    position: relative;
}
#child
{
    position: absolute;
    left: 0;
    right: 0;
}

http://jsfiddle.net/G3TBn/6/
But, then that can cause layout flow issues (which may or may not be an issue):
http://jsfiddle.net/G3TBn/7/
You can set a fixed width at runtime (as opposed to design time) with JavaScript.  Measure the inline element whose width you want to use, and set that as the fixed width of the parent element.
document.getElementById("parent").style.width =
    document.getElementById("setter").offsetWidth + "px";

http://jsfiddle.net/G3TBn/2/

A: All you need is
#child {margin: 0; padding: 0; }

and maybe width: 100% if you've set a different width elsewhere.
Also, it's
 ("List Item"), not <il>. :-)
EDIT: If this is a drop down list, you need to wrap the  around the sub ` anyway. Here's a better way to go:
<!DOCTYPE html>

<meta charset="utf-8">

          $variable

one

two

A: I would do so:
#setter {
    position:relative;
    display:inline-block;
    background:yellow;
    padding:0 15px;
}
#child {
    position:absolute;
    background:red;
    width:inherit;
}

might have to adjust padding. but I hope you get the idea.
demonstration


text:
Q: overridePendingTransition() doesn't work in TimerTask I want to show Activity Animation when satrtactivity  or   finish ,but  it invalid probably in TimerTask Thread(I knwon it work in UI Thread)
Timer timer = new Timer();
timer.schedule(new TimerTask() {
            @Override
            public void run() {
                startActivity(new Intent(myActionAnimation.this,activitytest.class));
                overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            }
        }, 100);

can anyboby explain it?    thx.

A: You simply use this:
    Handler h = new Handler();
    h.postDelayed(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            startActivity(new Intent(myActionAnimation.this,
                    activitytest.class));
            myActionAnimation.this.overridePendingTransition(
                    android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            finish();
        }
    }, 5000);

A: I have also face this problem and after some research i found one solution and it is working
You should use Handler for this like
  Handler handler=new Handler(){
    public void handleMessage(android.os.Message msg) {

        startActivity(new Intent(myActionAnimation.this,
                activitytest.class));
        myActionAnimation.this.overridePendingTransition(
                android.R.anim.slide_in_left, android.R.anim.slide_out_right);
        finish();

    };
};

and in the thread you need to call this like
   Timer timer = new Timer();
   timer.schedule(new TimerTask() {
        @Override
        public void run() {
          handler.sendMessage(new Message());
        }
    }, 100);

I think it may help you
happy coding


text:
Q: Wix launch application window is hidden I've got an MSI installer built with Wix, and as is common I want a tickbox on the Finished page to launch the app. I've followed the method here to do this: http://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/run_program_after_install.html
It works, but the problem is the application window is hidden by any other windows that are on the screen, when it starts up it doesn't show at the front. I don't know why this is happening? Is there a way to fix this, or do I have to create another custom action to bring the window to the front?