text:
Q: Matching exactly 2 characters in string - SQL How can i query a column with Names of people to get only the names those contain exactly 2 "a" ?
I am familiar with % symbol that's used with LIKE but that finds all names even with 1 a , when i write %a , but i need to find only those have exactly 2 characters.
Please explain - Thanks in advance

Table Name: "People"
Column Names: "Names, Age, Gender"

A: Assuming you're asking for two a characters search for a string with two a's but not with three.
select *
  from people
 where names like '%a%a%'
   and name not like '%a%a%a%'

A: Use '_a'. '_' is a single character wildcard where '%' matches 0 or more characters.
If you need more advanced matches, use regular expressions, using REGEXP_LIKE. See Using Regular Expressions With Oracle Database.
And of course you can use other tricks as well. For instance, you can compare the length of the string with the length of the same string but with 'a's removed from it. If the difference is 2 then the string contained two 'a's. But as you can see things get ugly real soon, since length returns 'null' when a string is empty, so you have to make an exception for that, if you want to check for names that are exactly 'aa'.
select * from People
where
  length(Names) - 2 = nvl(length(replace(Names, 'a', '')), 0)

A: Another solution is to replace everything that is not an a with nothing and check if the resulting String is exactly two characters long:
select names
from people
where length(regexp_replace(names, '[^a]', '')) = 2;

This can also be extended to deal with uppercase As:
select names
from people
where length(regexp_replace(names, '[^aA]', '')) = 2;

SQLFiddle example: http://sqlfiddle.com/#!4/09bc6

A: select * from People where names like '__'; also ll work


text:
Q: Python script with a loop and a conditional statemen i am trying to create a script with  a loop and a conditional statement to find the value of the number of dogs in the following collection of key-value pairs but i am just not getting my head around it.
so how do i find the value of the number of dogs in the following collection of key-value pairs,
Cheers
Vlad

 for value in KC.values():
  if 'Dogs' in value:
       return value

A: You have .values(), which will give you the values. E.g 7, 12, 21, 3, 3
Otherwise you can use .keys(), which will give you "Cats", "hamsters" etc.
Or you can simply check:
if "dogs" in KC:
    return KC["dogs"]

Keep in mind that coding is case sensitive. So "Dogs" and "dogs" are not the same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to understand the first type of pair? I am learning C++ recently and am confused by this data type:
pair<map<string, size_t>::iterator, bool> ret =
            word_count.insert(make_pair(word, 1));

It should be easy to see that we're defining a pair and that the second type of the
pair is bool. The first type of that pair is a bit harder for me to understand.
If there were no scope operator or iterator, it would be easy. But after adding :: iterator is it iterator type or the map<string, size_t> type?

A: iterator is a nested type inside of the std::map class.
The first member of the pair is an iterator to an element in the map. The insert() method returns an iterator to the element that was inserted, or to the  element that prevented the insertion.
The bool in the pair indicates whether the insertion was successful or not, ie whether the returned iterator is to a new element or an existing element, respectively.

A: As you write yourself, the first type is map<string, size_t>::iterator
So what you have is a pair of <iterator, bool>, where the iterator is a map<string, size_t> iterator.

A: Somewhere in the definition of map<string, size_t> is a statement like typedef [something] iterator; or using iterator = [something];. It introduces map<string, size_t>::iterator as the name for the iterator type associated with map<string, size_t>. So it's an iterator type, but it's specifically the iterator for the map<string, size_t> container.


text:
Q: Grunt replace last occurrence of matching string I have a custom requirement where I need to replace the last occurrence of of a closing brace with empty string,
How can i achieve using Grunt-replace ?
In the below Templates.js file I am replacing
    angular.module('abc.templates', []).run(
with
return

Templates.js
Now I have to remove the unnecessary closing brace at line:20 below.
 angular.module('abc.templates', []).run(['$templateCache', function($templateCache) {
      $templateCache.put("test",
          //
          //
          //
      $templateCache.put("test",
          //
          //
          //
      $templateCache.put("test",
          //
          //
          //
      $templateCache.put("test",
        //
        //
        //
 line 20:   }]);

In the above Templates.js file I want to remove the last occurence of closing brace ')' at line 20 mentioned above.
Can someone help me with any regex or some other way to achieve this ?

A: Using grunt-replace you could try the following configuration:
Gruntfile.js
module.exports = function (grunt) {

  grunt.initConfig({
    replace: {
      templateJs: {
        options: {
          usePrefix: false,
          patterns: [
            {
              match: /angular\.module\('abc\.templates', \[\]\)\.run\(/g,
              replacement: 'return '
            },
            {
              match: /(angular\.module\('abc\.templates', \[\]\)\.run\([\w\W]+?}])(\))(;)/g,
              replacement: '$1$3'
            }
          ]
        },
        files: [
          // Define your paths as necessary...
          {expand: true, flatten: true, src: ['src/template.js'], dest: 'build/'}
        ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-replace');
  grunt.registerTask('default', 'replace:templateJs');
};

Additional info

*

*The first match regex pattern used in the patterns Array is explained here. This handles the first part of replacing angular.module('abc.templates', []).run( with return

*The second match regex pattern used in the patterns Array is explained here. This removes the closing brace ) from }]); to end up with }];

Note: The second regex will match the first instance of the characters }]); after the initial angular.module('abc.templates', []).run( part and remove the ) from it. So, unfortunately if the pattern }]); occurs elsewhere in the body of your function this will not meet your requirement. Otherwise it should be ok.


text:
Q: MySQL Get the first record in the last 10 records in Mysql, I am trying to get the oldest record of the last 10 records.
To get the last 10 I would simply do
SELECT * FROM table ORDER BY id DESC LIMIT 10;
to get the oldest I simply use the ASC order.
I need to first order in DESC order to get the last 10 and then order by ASC to get the first record of that array.
which query would I use to get row number 10 in DESC order, namely, the oldest of the 10 newest?

A: Use [LIMIT {[offset,] row_count] concept:
SELECT * FROM table
ORDER BY id
DESC LIMIT 9, 1

Here, OFFSET is 9 --> that means 10th row (which will be first row in the last 10 rows when ordered back in Ascending order).

A: select only 1 using a subquery
SELECT * FROM ( SELECT * FROM ORDER BY id DESC LIMIT 10 ) order by id ASC LIMIT 1 ;


text:
Q: Same set of JS only work for one while others don't work on IE I am rather new to web building so this question might be quite easy for you to answer, but I have tried look-up for possible solutions and found no clue at all, here is my only hope.
I am trying to manipulate the effect in FB where you navigate posts with previous/next arrows and a close button. I made myself the buttons with image, and I want to script it so it will move on/back/close the content box when clicked without actually jumping from page to page.
I basically borrowed a fellow stackoverflower's (too lazy to find the page again, sorry :P) script to make it, and it works fine with chrome. The problem is, it doesn't work with my IE, and I have no clue why.
Here is the part that not working in IE (I think):
http://jsfiddle.net/ZfRW5/1/
(please ignore the image link)
In IE, I can click picture to access the overlay, but once the overlay is opened, the navigation buttons (next, previous and exit buttons) become un-clickable.
It is utterly weird to me because I am using the same script for all these while apparently some works some doesn't.
This is the main script I use:

Can anyone help me out with this? I am terribly confused.

A: Using position:fixed; on children of  tags doesn't play nice in several browsers.
Try applying your position:fixed to the  itself, not the  within, and it should work fine.


text:
Q: Авторизация на сайте через cookie средствами Python Требуется написать скрипт для входа на сайт и дальнейшей работы на нем. На нем стоит защита от автоматических систем (https://binomo.com/ru НЕ РЕКЛАМА). Да и опыта у меня мало, написал пару скриптов для телеги, ВК и обработки видео. Но вот я подумал возможно ли вместо авторизации использовать cookie от браузера? Только как это сделать и проверить что работает? Нашел модуль browsercookie, но по нему мало примеров чтобы разобраться.
Пока имею следующее:
import browsercookie
import requests
cj = browsercookie.firefox()
r=requests.post('https://binomo.com/ru/trading', cookies=cj)
print(r.status_code)

выдает 500.
Помогите, пожалуйста, советом или ткните в путевый материал если есть такой.


text:
Q: C# and Generics: how can I handle processing based on type? I'm new to generics and I'm trying to make a generic HTTP GET method for my project (and possibly expand it to handle POST/PUT also). The following seems to work OK when the response is string based:
private async Task<T> HttpGetAsync<T>(Uri uri)
{
    var httpRequestMessage = new HttpRequestMessage()
    {
        Method = HttpMethod.Get,
        RequestUri = uri,
        Headers =
        {
            { "Authorization", $"Basic {encodedCredentials}"},
            { "Cache-Control", "no-cache" }
        }
    };

    var response = await _httpClient.SendAsync(httpRequestMessage);
    var content = await response.Content.ReadAsStringAsync();
    return JsonConvert.DeserializeObject<T>(content);
}

But in some cases, based on the type, I would like the response to be read using ReadAsByteArrayAsync() or ReadAsStreamAsync() instead of ReadAsStringAsync().
I think that I could probably do a getType() within the method, and read the response using the appropriate method, but I'm wondering if maybe there is a better way to do this?
Is this a bad idea/a bad usage of generics in general? Thanks for any information!

A: Use an interface:
interface IContentReader<T>
{
    T ReadAsync(HttpResponseMessage response);
}

private async Task<T> HttpGetAsync<T>(Uri uri, IContentReader<T> reader)
{
    var httpRequestMessage = new HttpRequestMessage()
    {
        Method = HttpMethod.Get,
        RequestUri = uri,
        Headers =
        {
            { "Authorization", $"Basic {encodedCredentials}"},
            { "Cache-Control", "no-cache" }
        }
    };

    var response = await _httpClient.SendAsync(httpRequestMessage);
    return await reader.ReadAsync(response);
}

And you can have different implementations of IContentReader<T>.
You can determine which implementation to use based on T.


text:
Q: Hibernate - One to many relationship and orphanRemoval cascade I have a basic one to many relation parent / child like in the chapter 21 of Hibernate references book.
The cascade is only from child to parent (persist cascade only because I don't want to delete the parent if I delete a child).
When I add a child to the parent and I save the child, I have a TransientObjectException...
@Entity
public class Parent implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @OneToMany(mappedBy = "parent", orphanRemoval = true)
  private List<Child> childs;

  public List<Child> getChilds() {
    return childs;
  }

  public void setChilds(List<Child> childs) {
    this.childs = childs;
  }

  public void addChild(Child child) {
    if (childs == null) childs = new ArrayList<Child>();
    if (childs.add(child)) child.setParent(this);
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }
}

@Entity
public class Child implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @ManyToOne(optional = false)
  @Cascade( { PERSIST, MERGE, REFRESH, SAVE_UPDATE, REPLICATE, LOCK, DETACH })
  private Parent parent;

  public Parent getParent() {
    return parent;
  }

  public void setParent(Parent parent) {
    this.parent = parent;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }
}

@Test
public void test() {
  Parent parent = new Parent();
  Child child = new Child();
  parent.addChild(child);
  genericDao.saveOrUpdate(child);
}

But on the saveOrUpdate, I have this exception:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Child
  at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:244)
  at org.hibernate.collection.AbstractPersistentCollection.getOrphans(AbstractPersistentCollection.java:911)
  at org.hibernate.collection.PersistentBag.getOrphans(PersistentBag.java:143)
  at org.hibernate.engine.CollectionEntry.getOrphans(CollectionEntry.java:373)
  at org.hibernate.engine.Cascade.deleteOrphans(Cascade.java:471)
  at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:455)
  at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:362)
  at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:338)
  at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
  at org.hibernate.engine.Cascade.cascade(Cascade.java:161)
  at org.hibernate.event.def.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:476)
  at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:354)
  at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
  at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
  at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:677)
  at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:669)
  at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:252)
  at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:392)
  at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:335)
  at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
  at org.hibernate.engine.Cascade.cascade(Cascade.java:161)
  at org.hibernate.event.def.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:451)
  at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
  at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
  at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
  at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:677)
  at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:669)
  at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:665)

I really don't understand because saving the Child should save the Parent via the cascade...
Any ideas ?
UPDATE 1
The problem seems to be related to "orphanRemoval" because if I comment it on the parent:
@OneToMany(mappedBy = "parent" /*, orphanRemoval = true */)
private List<Child> childs;

It works!
It save the child, then the parent.
But I really need the orphan to be deleted via the cascade when I remove a child from its parent.
UPDATE 2
I've created a JIRA issue:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-5364
UPDATE 3
It seems to be fixed :-)
http://opensource.atlassian.com/projects/hibernate/browse/HHH-2269

A: It was an issue in Hibernate and it is now fixed:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-2269

A: Basically you are violating a constraint. The row in the db that corresponds to the parent doesn't exist, so there is no foreign key relationship that the child can use to refer to the parent. Add a call to saveOrUpdate on the parent before doing do for the child.
(edit) I missed your comment about cascade before the reformatting. My recollection is that cascade doesn't work upstream that way; you would still need to save the parent first.


text:
Q: Entity Framework 6 Migrations class Library project I have a solution with an asp.net core mvc project working against the full .net framework and a class library project with all my domain logic, entities, context and all that since I want to have full EF6 with my core mvc project. I created all my entity classes and modeled their relationships and all. I enabled migrations which was successful and added my first migration which also went well. Upon issuing the command update-database, I get this error:

PM> Update-Database
      Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
      System.InvalidOperationException: Sequence contains no matching element
      at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)
      at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
      at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
      at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.BinaryPropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
      at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
      at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass4.b__3(Tuple2 pm)
      at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable1 ts, Action1 action)
      at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
      at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
      at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
      at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection1 entitySets, DbProviderManifest providerManifest) at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
      at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
      at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
      at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
      at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
      at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
      at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w) at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action1 writeXml)
      at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context) at    System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase) at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration) at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
      at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
      at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
      at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
      at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
      at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force) at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0() at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
      Sequence contains no matching element

I am not a sure what this message means so can anyone help me understand what I am doing wrong?!


text:
Q: How to replace "¿" using str_replace() in PHP? This is the code I am trying.
echo str_replace("¿","","¿ teste ¿ teste");

I want to find the ¿ in any given string and remove it. But, this code is not working right.
What could I be doing wrong?
EDIT:
I managed using html special code;
The link:
http://www.utexas.edu/learn/html/spchar.html
Thanks!

A: It works just fine.
php -r 'echo str_replace("¿","","¿Is it Tuesday?");'

Output:
Is it Tuesday?

EDIT
You can try making sure the file itself is 100% ASCII by escaping characters:
<?php

$c  =  json_decode('"' . '\u00bf' . '"'); // the question mark

echo str_replace( $c, '', $my_string ) . "\n";

(Taken from PHP decoding and encoding json with unicode characters)

A: You might be saving the php file with an encoding that does not correctly store your string. Save your php file using a UTF encoding and try again.


text:
Q: Docker error The command non-zero code: 1 python i have problem when i tried to build container. And the error is :
The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1

i don't know why, i follow the code from documentation but always get error.
Dockerfile
FROM python:2.7-slim
#
# # Set the working directory to /app
WORKDIR /app
#
# # Copy the current directory contents into the container at /app
ADD . /app
#
# # Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt
#
# # Make port 80 available to the world outside this container
EXPOSE 80
#
# # Define environment variable
ENV NAME World
#
# # Run app.py when the container launches
CMD ["python", "app.py"]

A: Seems issue with the location of the file try to give absolute path of the file that you are referring in dockerfile


text:
Q: Is it possible to create static classes in PHP (like in C#)? I want to create a static class in PHP and have it behave like it does in C#, so

*

*Constructor is automatically called on the first call to the class

*No instantiation required

Something of this sort...
static class Hello {
    private static $greeting = 'Hello';

    private __construct() {
        $greeting .= ' There!';
    }

    public static greet(){
        echo $greeting;
    }
}

Hello::greet(); // Hello There!

A: In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.
So in my humble opinion this is a more complete example based on Greg's one:
<?php

class Hello
{
    /**
     * Construct won't be called inside this class and is uncallable from
     * the outside. This prevents instantiating this class.
     * This is by purpose, because we want a static class.
     */
    private function __construct() {}
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!

?>

A: final Class B{

    static $staticVar;
    static function getA(){
        self::$staticVar = New A;
    }
}

the stucture of b is calld a singeton handler you can also do it in a
Class a{
    static $instance;
    static function getA(...){
        if(!isset(self::$staticVar)){
            self::$staticVar = New A(...);
        }
        return self::$staticVar;
    }
}

this is the singleton use
    $a = a::getA(...);

A: I generally prefer to write regular non static classes and use a factory class to instantiate single ( sudo static ) instances of the object.
This way constructor and destructor work as per normal, and I can create additional non static instances if I wish ( for example a second DB connection )
I use this all the time and is especially useful for creating custom DB store session handlers, as when the page terminates the destructor will push the session to the database.
Another advantage is you can ignore the order you call things as everything will be setup on demand.
class Factory {
    static function &getDB ($construct_params = null)
    {
        static $instance;
        if( ! is_object($instance) )
        {
            include_once("clsDB.php");
            $instance = new clsDB($construct_params);   // constructor will be called
        }
        return $instance;
    }
}

The DB class...
class clsDB {

    $regular_public_variables = "whatever";

    function __construct($construct_params) {...}
    function __destruct() {...}

    function getvar() { return $this->regular_public_variables; }
}

Anywhere you want to use it just call...
$static_instance = &Factory::getDB($somekickoff);

Then just treat all methods as non static ( because they are )
echo $static_instance->getvar();

A: you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...
see Singleton in PHP

A: You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).
Therefore you'd have to create an initialize() function and call it in each method:
<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!

?>

A: object cannot be defined staticly
but this works
final Class B{
  static $var;
  static function init(){
    self::$var = new A();
}
B::init();


text:
Q: SO tells you who deleted their answers...maybe? I answered a question this morning about how to get the number of rows returned from a mysql query in PHP. Relatively easy question, so I wasn't amazed when Paolo Bergantino left a comment that he was working on getting his answer in when I got mine in. Fair game.
From the front page of SO, the question was advertised as having 2 answers, the second from Adam Plumb. But when you go into the question...there's only my answer. When you go to Adam's profile, his recent tab doesn't show that he answered this question. The front page, however, still says he answered the question.
I'm assuming he answered it, but saw that I had already given the same answer. When this happened, he deleted his answer and up-voted mine, likely. Should the front page still contain his answer with the question?

A: I expect the front page was a caching issue. For performance reasons many of the numbers you see (vote counts / etc against posts; article counts against tags; etc) are heavily cached and re-used - so may be a minute or so out of date.
To confirm; yes, he deleted it himself.


text:
Q: In Racket, if I invoke `lambda` with multiple body arguments, what happens? The Racket Docs state that the lambda function can be invoked with multiple arguments after the body argument, e.g.:
((lambda () (display "foo") (display "bar")))

prints foobar.
How exactly does this work? I didn't find any explanation in the racket documentation. Did I miss something?

A: Procedure bodies have an implicit begin. Thus
(lambda ()
  (foo)
  (bar))

is treated as if the same as
(lambda ()
  (begin
    (foo)
    (bar)))

See Sequencing in the Racket guide for more details.


text:
Q: Angular 12: How to deploy custom index.html outside language-specific directories in multi-language app? I've been working on a multi-language Angular 12 app, which I've deployed to Firebase hosting.
The app uses Angular's i18n feature. The build process creates separate directories for each language. The command ng build --localize creates those folders:
 dist/myApp/en
 dist/myApp/de

Now, I would like an index.html at the domain root, which does redirection based on the browser's language setting. How can I do that?
I already have an appropriate script, but don't know how to deploy anything outside the /de or /en folders.
Here is a shortened version of my `angular.json:
...
  "projects": {
        "myApp": {
          "projectType": "application",
          "schematics": {
            "@schematics/angular:application": {
              "strict": true
            }
          },
          "root": "",
          "sourceRoot": "src",
          "prefix": "app",
          "i18n": {
            "sourceLocale": "en",
            "locales": {
              "de": "src/locale/messages.de.xlf"
            }
          },
          "architect": {
            "build": {
              "builder": "@angular-devkit/build-angular:browser",
              "options": {
                "i18nMissingTranslation": "error",
                "localize": true,
                "outputPath": "dist/myApp",
                "index": "src/index.html",
                "main": "src/main.ts",
                "polyfills": "src/polyfills.ts",
                "tsConfig": "tsconfig.app.json",
                "assets": [
                  "src/favicon.ico",
                  "src/assets",
                  "src/manifest.webmanifest",
                ],
             ...
              },
              "configurations": {
                "production": {
                  "fileReplacements": [
                    {
                      "replace": "src/environments/environment.ts",
                      "with": "src/environments/environment.prod.ts"
                    }
                  ],
                  ...
                },
                "de": {
                  "localize": [
                    "de"
                  ],
                  "baseHref": "/de/"
                },
                "en": {
                  "localize": [
                    "en"
                  ],
                  "baseHref": "/en/"
                }
              },
              "defaultConfiguration": ""
            },
            "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "options": {
                "browserTarget": "myApp:build"
              },
              "configurations": {
                "production": {
                  "browserTarget": "myApp:build:production"
                },
                "en": {
                  "browserTarget": "myApp:build:en"
                },
                "de": {
                  "browserTarget": "myApp:build:de"
                }
              }
            },
            ...
          }
        }
      }
...

Excerpt of my firebase.json:
...
    "hosting": {
        "public": "dist/myApp",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "rewrites": [
          {
            "source": "/de/**",
            "destination": "/de/index.html"
          },
          {
            "source": "/en/**",
            "destination": "/en/index.html"
          }
        ],
        "i18n": {
          "root": "/"
        }
      },
...


text:
Q: Accessing Properties after jQuery keydown I have a object called player
function Player(_x, _y, _speed) {
    this.x = _x;

    this.getX = function() {
        return this.x;
    };

    this.handleKeyDown = function(event) {
        console.log(this.x); // undefined
    };

    $(document.body).keydown(this.handleKeyDown);
}

Why doesn't "handleKeyDown" not see my x Property? And how do I work around it?

A: Because the this in your keydown handler is the element itself (in this case, document.body). You need to either
var self = this;
$(document.body).keydown(function() { self.handleKeyDown() });

Or look at using bind or $.proxy

A: Because this doesn't work the way you think it does in javascript.  this is the context in which the current function is being executed.  So when you do something like... object.doThing(), then while executing doThing() this is pointing to object.  However you could call doThing() without the object reference, then this is the global object.
Below is the code you gave rewritten to use the concept of closures to avoid the this schenanigans.  This code can be further refactored to use prototypes and avoid the extra memory overhead of creating all the same functions over and over again but I don't want to junk this up with more information than is needed.
function Player(_x, _y, _speed) {
    var x = _x;

    var getX = function() {
        return x;
    };

    var handleKeyDown = function(event) {
        console.log(x);
    };

    $(document.body).keydown(handleKeyDown);
}

An eye-opening method in Javascript that shows that this does not operate the way you initially thought would be the MDN docs for Function.prototype.apply.

A: If using ES5, you can use .bind (or on older browsers, shim it, or use $.proxy) to ensure that this is correctly set:
this.handleKeyDown = function(event) {
    console.log(this.x);
}.bind(this);

or you can maintain an external reference to this in your lexical scope:
var self = this;
this.handleKeyDown = function(event) {
    console.log(self.x);
};

A: the this is 'document.body' here, not the object Player

A: Because this represents the getX function, try this :
function Player(_x, _y, _speed) {
    var self = this;
    self.x = _x;

    self.getX = function() {
        return self.x;
    };

    self.handleKeyDown = function(event) {
        console.log(self.x);
    };

    $(document.body).keydown(self.handleKeyDown);
}

Edit : meh, I read to fast, I meant handleKeyDown. Anyway, the thing is that the context of this changes, so it is a good practice to store it in a self field to clarify your code and make sure you are refering to what you think.


text:
Q: T-SQL Query - How to not include some results from different row I have a data something like below.
ID | Value
------------
 1 | A
 1 | B
 1 | C
 2 | A
 2 | C
 3 | C

I'm trying to get ID which has A but not including B.
In this case, I should only get ID 2 as a result.
If I query like
SELECT DISTINCT ID
FROM TABLE
WHERE (VALUE = 'A' AND VALUE <> 'B')

I get 1 and 2 as a result.
Is this even possible from this database structure?

A: You need to exclude any ID's that contain the value 'B'. you can do this with a left join and a check for null... i.e. no match.
select d.*
from data d
    left join (select id from data where value = 'B') x --exclude these
        on d.id = x.id
where x.id is null
    and d.value = 'A'

A: Even though you accepted an answer, I'll write another variant. I think it is easier to write and understand. In terms of performance you have to check how different variants work on your system with your real data.
DECLARE @T TABLE (ID int, Value char(1));

INSERT INTO @T (ID, Value) VALUES (1, 'A');
INSERT INTO @T (ID, Value) VALUES (1, 'B');
INSERT INTO @T (ID, Value) VALUES (1, 'C');
INSERT INTO @T (ID, Value) VALUES (2, 'A');
INSERT INTO @T (ID, Value) VALUES (2, 'C');
INSERT INTO @T (ID, Value) VALUES (3, 'C');

SELECT ID FROM @T WHERE Value = 'A'

EXCEPT

SELECT ID FROM @T WHERE Value = 'B'

Result set:
ID
2

A: here is another query for it:
select distinct tb.ID from tbl_name tb
where tb.Value='A' and tb.ID not in(select distinct tbl.ID from tbl_name tbl
where tbl.Value='B')

A: There is also the possibility of using WHERE NOT EXISTS:
SELECT t1.id FROM table t1
 WHERE t1.value = 'A'
   AND NOT EXISTS ( SELECT 1 FROM table t2
                     WHERE t2.id = t1.id
                       AND t2.value = 'B' );


text:
Q: Update JSONb value I would like to update a JSONb value inside a PostgreSQL table, here his prototype :
{
    key1: {
        key2: {
            key3: value
            ...
        }
        ...
    }
    ...
}

I would like to update key1->key2->>key3.

A: You can use jsonb_set() for that:
update the_table
   set the_column = jsonb_set(the_column, '{key1,key2}', '{"key3": "new_value"}')
where the_pk_column = 42;

Online example: https://rextester.com/CEWF51936


text:
Q: .NET How can i set field value on value type using reflection .NET I want to clone a value type's fields. How can i set a field value on a value type using reflection (or something else dynamically)?
This works for reference types but not for value types. I understand why but I don't know an alternative.
shared function clone(of t)(original as t) as t
  dim cloned as t

  'if class then execute parameterless constructor
  if getType(t).isClass then cloned = reflector.construct(of t)()

  dim public_fields = original.getType.getFields()

  for each field in public_fields
     dim original_value = field.getValue(original)
     'this won't work for value type, but it does work for reference type ???
     field.setValue(cloned, original_value)
  next

  return cloned
end function

A: If it is a value type then you are done quick, just return "original":
'if class then execute parameterless constructor
If GetType(t).IsClass Then
  Dim types(-1) As Type
  cloned = DirectCast(GetType(t).GetConstructor(types).Invoke(Nothing), t)
Else
  Return original
End If

You'll have more trouble making this truly universal, a type doesn't have to have a parameter-less constructor.  Try a String for example.

A: Since value types are passed by value, SetValue is being called on a copy of the object.
If T is a value type, you can simply write Return original and it will return a copy.
For example:
If GetType(T).IsValueType Then Return original


text:
Q: Installing and using pip, "SyntaxError: invalid syntax" I followed these instructions for installing pip on Windows 7. When I try to install the example package with pip install httpie (or any other package), it gives me the following error:
SyntaxError: invalid syntax

It also highlights the word install. And that's it. I am using Python 3.3.1 and used the corresponding installers in the instructions at the link above. Finally, I apologize if you consider this a duplicate, but Stack Overflow will not allow me to post on the answer in the original thread and I am getting an error message that they do not discuss.

A: You're typing those commands in Python. They are not Python commands, they are shell commands. Type them in your shell!

A: You should type that in the command prompt, not in Python.


text:
Q: Auto-generate unique ID for each class type I have an interesting problem. I would like to write a class, which when inherited provides to all children classes the following behavior:

*

*sets its self.id attribute to a UUID value
-- if this is the first time class got instantiated, a new UUID is generated
-- the UUID value is reused for the same class, when it is instantiated many times

Now, the fun part: I want the mechanism above to work, regardless of the path used to instantiate this class. Let's assume the following:
from .Package.Class1 import Class1
from TopPackage.Package.Class1 import Class1

from .Package.Class2 import Class2
from TopPackage.Package.Class2 import Class2

In both situations, I would like Class1 to generate the same self.id value in both import styles. I would also like Class2 to generate a different self.id value from Class1, but the same between its own import styles.
So far, I wrote the following code for a class classes 1 and 2 would inherit from:
class ClassWithId(ABC):
    _EXISTING_OBJECT_IDS = dict()

    def __init__(self):
        if self in ClassWithId._EXISTING_OBJECT_IDS.keys():
            self.id = ClassWithId._EXISTING_OBJECT_IDS[self]
        else:
            self.id = uuid.uuid4()
            ClassWithId[self] = self.id

However, I have a few problems in here:

*

*ClassWithId must inherit from class ABC because it is also an interface for classes 1 and 2

*trying to put self as key in dict() results in TypeError: 'ABCMeta' object does not support item assignment

*I am generally unsure, if this approach is going to be resistant to different import styles, because from Python's perspective class type .Package.Class1.Class1 and TopPackage.Package.Class1.Class1 are 2 different objects

Any ideas?
UPDATE:
I have integrated Elrond's suggestion into my code, and but different import levels (package-wise) yield different UUID values for the same class:
<class 'StageTwo.Steps.SsTestHandler1.SsTestHandler1'>   3583c89c-5ba8-4b28-a909-31cc27628370
<class 'tests.TestStages.StageTwo.Steps.SsTestHandler1.SsTestHandler1'>   f4ead4a0-f5f7-4d95-8252-0de47104cb2f

<class 'StageTwo.Steps.SsTestHandler2.SsTestHandler2'>   8bd9a774-0110-4eee-a30c-a4263ad546cf
<class 'tests.TestStages.StageTwo.Steps.SsTestHandler2.SsTestHandler2'>   773d84c4-82a3-4684-92b5-51509e6db545

Maybe I forgot to mention, but my ClassWithId is inherited by ClassX and ClassY down the line, and it is these 2 classes, which are expected to be resistant to the situation I have shown above (being imported with different path, yet still retaining the same UUID).

A: You will need to use a metaclass for this:
import uuid
import abc

class BaseMeta(abc.ABCMeta):
    def __new__(mcs, name, bases, attrs):
        attrs['_class_uuid'] = uuid.uuid4()
        return super().__new__(mcs, name, bases, attrs)

class Base(metaclass=BaseMeta):
    def __init__(self):
        print(self.__class__.__name__, self._class_uuid)

Now all classes that inherit from Base will be assigned a uuid via the _class_uuid property, once per subclass:
from package1.class1 import Class1
from package2.class2 import Class2

Class1() # 6e0852c8-61c9-4f8b-9817-eeeda4b49d56
Class1() # 6e0852c8-61c9-4f8b-9817-eeeda4b49d56

Class2() # 73012f1a-a984-4f76-96f1-ef5225a38fbe
Class2() # 73012f1a-a984-4f76-96f1-ef5225a38fbe

Using absolute/relative imports shouldn't make a difference in either case.

A:
from Python's perspective class type .Package.Class1.Class1 and TopPackage.Package.Class1.Class1 are 2 different objects

If I understand what you're saying here, I don't think this statement is true. Hopefully, my example below will clarify.
There might be other approaches, such as using the class name as your dictionary key, but perhaps a more extendable approach is with a metaclass.
I placed everything in one file, for the sake of simplicity, but the approach remains the same for a module with multiple levels:
TopPackage.py:
import uuid

class ABC:
    pass

def id_assigner(class_name, class_parents, class_attrs):
    class_attrs['id'] = str(uuid.uuid4())
    return type(class_name, class_parents, class_attrs)

class Class1(ABC, metaclass=id_assigner):
    pass

class Class2(ABC, metaclass=id_assigner):
    pass

def foo():
    c2 = Class2()

    print('c2.id from foo: ', c2.id)

And a script to test it:
import TopPackage

c1_a = TopPackage.Class1()
c1_b = TopPackage.Class1()

print(c1_a.id)
print(c1_b.id)

c2_a = TopPackage.Class2()
c2_b = TopPackage.Class2()

print(c2_a.id)
print(c2_b.id)

TopPackage.foo()

The call to TopPackage.foo(), I hope, shows that using Class2 from different location will result in the same class definition, and hence the same id. When I run this test script an example output I get is:
c69b17e0-9ff0-4276-bcce-6ac4f5e5a2e5
c69b17e0-9ff0-4276-bcce-6ac4f5e5a2e5
86fbe02e-d411-4ba1-b292-d2b1ec2100bd
86fbe02e-d411-4ba1-b292-d2b1ec2100bd
c2.id from foo:  86fbe02e-d411-4ba1-b292-d2b1ec2100bd


text:
Q: How can I display text on a certain date using Swift? I am currently trying to display a string on a certain date (Halloween). I have pasted the code I used below:
 var dateComponents = NSDateComponents()
    var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
    var currentDate = NSDate()
    var halloweenDate = calendar?.dateFromComponents(dateComponents)
    dateComponents.day = 1
    // I used 1 as the day only for testing
    dateComponents.month = 10
    dateComponents.year = 2015

I then created this If statement to see if the current date is equal to halloweenDate.
    if currentDate == halloweenDate {
        println("Happy Halloween!")

    }

I know that the println() does not display text on the screen, I am just using it for testing
I am not sure what I am doing wrong or leaving out.
This is what I have so far. As a fairly new programmer, this looks like it would work, but as I have found, if it seems easy, It probably wrong
Thanks.

A: Set the values of dateComponent just before callingdateFromComponent on halloweenDate.

A: Welcome to SO. Your question is kind of vague.
If your app happens to be launched/brought to the foreground on the date in question then you could use some date math to recognized the fact and display an alert.
If your app is not run then your best bet is to post a local notification with a fire date on your target date. Then when the date rolls around the system will display a message to the user and if the user taps on it, your app will be launched.
Both approaches above take some setup.
Can you clarify what it is you want to do?

A: You want to get the month and day components of the current date and compare them to 10 and 31, respectively, like this:
// This is in Swift 2
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let nowComponents = calendar.components([.Month, .Day], fromDate: now)
if nowComponents.month == 10 && nowComponents.day == 31 {
  print("Happy Halloween!")
}

A: Please use NSDateFormatter.
For example :
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"

var strDate = "01/10/2015"
var currentDate = dateFormatter.dateFromString(strDate)

It'll works fine for you.


text:
Q: My button Not responding on Hover or Click in Unity 2D UI Ok as you read title you will know problem. The problem is very old and much people tell fixes. But nothing works for me. So please help another time. I have EventSystem in hierchy. See picture
Let me show you my canvas picture of inspector

As you can see I have other Canvas so let me see you picture of that name "Shop Canvas"

My EventSystem in inspector

Panel of buttons in Inspector

And finally button in inspector(These 2 images for buttons because button in inspector is some long).

If you need more Info right below and I will edit the post. Thanks for your help

A: I had a similar issue of not being able to engage with a button. The reason being there was another UI component with ray cast enabled that did not allow inputs to reach the button.
For your case, I think it's the "The things...". Try disabling that and see if you can engage with the button again.

A: I had a similar issue, where I couldn't see button interactions in a scroll view. I eventually created a click event (which worked) to find the source of my problem. While it wasn't a Raycast problem, someone else might find this handy (or I will see it in the future!)
Mine (an issue I've accidentally ♂ created in the past) was that I set the color of the attached Image component to black and couldn't see the interaction states in the Button. So to restate, leave Image.Color white/opaque but change button states if you want dark menus.


text:
Q: How to authorize user using next auth with nodejs server? I am using next auth for user authentication in my nextjs app, but my end points are on nodejs server (while next auth logic is in api/auth/[...nextauth] file). How can I verify that the user who sent the request from nextjs app to my nodejs server is authorized or not.
Is there a way to send and verify jwt token set by next auth to node js backend and see if user is authenticated or not?

A: It should be technically possible. For example, you can pass the JWT created by NextAuth to the Node.JS APIs via the Authorization header and decode the JWT using the value of NEXTAUTH_SECRET.
const jwt = require("jsonwebtoken");

const decode = jwt.verify(token, "secret");


text:
Q: Script that create Desktop Links on Windows? i thinking about a simple script or routine to create desktop links on windows machines. is there a way to do it with perl or cmd batch?
like if i do
call shortcut.bat C:\putty.exe Putty

a new desktop link appears on desktop.

A: save this as shortcut.bat
@echo off

:: creates a temporary vbs script that drops a shortcut to the desktop
:: replace %1 with the path to your *.exe that you wish to shortcut
:: replace %userprofile%\Desktop\%2.lnk with the path and name of your shortcut
ECHO %userprofile%\Desktop\%2.lnk

:: CHECK FOR EXISTING myshortcut.vbs SCRIPT AND DELETE
cd %userprofile%\Desktop
    if exist %userprofile%\Desktop\myshortcut.vbs del %userprofile%\Desktop\myshortcut.vbs

:: CREATE myshortcut.vbs FILE CONTAINING ALL COMMANDS for the vb script to create a shortcut of your file

FOR /F "tokens=1* delims=;" %%B IN ("Set oWS = WScript.CreateObject("WScript.Shell")") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("sLinkFile = "%userprofile%\Desktop\%2.lnk"") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs

FOR /F "tokens=1* delims=;" %%B IN ("Set oLink = oWS.Createshortcut(sLinkFile)") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   oLink.TargetPath = "%1"") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   '   oLink.Arguments = """) do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   '   oLink.Description = """) do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   '   oLink.HotKey = "ALT+CTRL+F"") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   '   oLink.IconLocation = "%1,2"") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   '   oLink.WindowStyle = "1"") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   '   oLink.WorkingDirectory = "%1"") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs
FOR /F "tokens=1* delims=;" %%B IN ("   oLink.Save") do echo %%B>>%userprofile%\Desktop\myshortcut.vbs

:: EXECUTE myshortcut.vbs
CSCRIPT %userprofile%\Desktop\myshortcut.vbs

:: Delete vbs script
del %userprofile%\Desktop\myshortcut.vbs

exit

use it like
call shortcut.bat C:\PROGRA~2\TeraTerm\ttermpro.exe TeraTerm >nul

A: @AlexTape answer is completely correct. This is the same answer, with nothing to add, just to simplify it
@echo off
    call :createDesktopShortcut "%~1" "%~2"
    exit /b

:createDesktopShortcut pathToExeFile nameOfShortcut
    if not exist "%~f1" goto :eof
    setlocal & set "tempFile=%temp%\%~nx0.vbs.tmp" & set "name=%~2" & if not defined name set "name=%~n1"
    echo(With WScript.CreateObject("WScript.Shell").Createshortcut("%userprofile%\desktop\%~2.lnk"):.TargetPath="%~f1":.Save:End With>"%tempFile%"
    cscript //nologo //e:vbscript "%tempFile%">nul & del /f /q "%tempFile%" >nul 2>nul
    endlocal & goto :eof

Same usage.
call desktopShortcut.cmd "c:\windows\system32\calc.exe" "my calculator"


text:
Q: function(&param) - like in PHP
Possible Duplicate:
JavaScript Pass Variables Through Reference

How can you do something like this in javascript?
In PHP you can put a & in a function in front of the parameter to write directly back to the variable.. How can you do something like this in javascript?

A: In JavaScript, values are passed to functions by value. Objects, however, are passed by reference.
Passing values:
function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4

Passing objects:
function myobject()
{
    this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
    fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

Source: http://snook.ca/archives/javascript/javascript_pass

A: If you pass an object into a function it is always treated as passing a reference to it.
To have a similar effect for primitive values, you might wrap them in an object before like
 var intVal = { val: 0 };

That way you can pass it to a function and still modify the actual variable.


text:
Q: Check if a string is in a file I've been trying to make a program that checks if a file contains another file's. (like an anti Virus). I tried to use strstr() to do so but apparently the strstr() does not work so well.
What is the best solution to check if a file contains another file in it?
Edit: I'm working on binary files.

A: The way to compare arbitrary sequences of bytes in C is with memcmp. This is a Standard C89 function.

A: You can implement Knuth-Morris-Pratt algorithm which is one of the best solutions for the problem you have.
It might be worth exploring and learning about other solutions to the string matching problem as well.
See: https://en.wikipedia.org/wiki/String_searching_algorithm for the list of string searching algorithms.
Resources to learn about KMP algorithm:

*

*https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

*https://www.youtube.com/watch?v=2ogqPWJSftE
Note: you can use these algorithms on bytes as well.

A: There is the memmem function, which finds a subsequence in a data file.
Compared with strstr, the memmem function does not stop at \0, which let's you find any data in any file.


text:
Q: A log-normal distribution in Python I have seen several questions in stackoverflow regarding how to fit a log-normal distribution. Still there are two clarifications that I need known.
I have a sample data, the logarithm of which follows a normal distribution. So I can fit the data using scipy.stats.lognorm.fit (i.e a log-normal distribution)
The fit is working fine, and also gives me the standard deviation. Here is my piece of code with the results.
sample = np.log10(data) #taking the log10 of the data

scatter,loc,mean = stats.lognorm.fit(sample,floc=0) #Gives the paramters of the fit

x_fit = np.linspace(sample.min(),sample.max(),100)
pdf_fitted = stats.lognorm.pdf(x_fit,scatter,loc,mean) #Gives the PDF

print "scatter for data is %s" %scatter
print "mean of data is %s" %mean

THE RESULT
scatter for data is 0.0157
mean for data is 14.18

The stddev which I call scatter is 0.0157, which is really low! why is this so?
In THIS POST and in THIS QUESTION it is mentioned that the log(mean) is the actual mean.
But you can see from my above code, the fit that I have obtained is using a the sample = log(data) and it also seems to fit well. However when I tried
sample = data #INSTEAD OF LOG(DATA)
pdf_fitted = stats.lognorm.pdf(x_fit,scatter,loc,np.log10(mean))

The fit does not seem to work.
1) The fit seems to look clear, but why is the stddev really low?
2) I also have suggestions that I should not be using log10(data), but why, the fit seems to be fine ?


text:
Q: Component Directive with Template and data bindings

In Angular2 is it possible to source below out into a directive?
<button [attr.disabled]="!infoForm.valid"></button>

e.g. have later:
<button [isValid]="!infoForm.valid"></button>

Edit
Would it be possible to end up with a more complex directive like such:?
@Component({
    selector: 'isValid',
    template: `
    <div>
        <button primary class="primary" (click)="next($event)">{{title}}</button>
    </div>`
})

export class ContinuationCheckDirective {

    @Input() isValid:boolean = false;

    @HostBinding('attr.disabled')
    disabled: boolean;

    ngOnChanges() {
        this.disabled = !this.isValid;
    }

    next() { // dostuff }

And then in parent component:
 <continuationCheckDirective [isValid]="!addresForm.valid"></continuationCheckDirective>

A: @Directive({
  selector: '[isValid]'
})
class IsValidDirective {

  @Input() isValid:boolean = false;

  @HostBinding('attr.disabled')
  disabled: boolean;

  ngOnChanges() {
    this.disabled = !this.isValid;
  }
}

Plunker example


text:
Q: Hackerrank: Sherlock and Anagrams Problem description: https://www.hackerrank.com/challenges/sherlock-and-anagrams
Adding a snapshot of the problem statement:

I am getting only few test cases correct. My algorithm is:

*

*Find all substrings of given string.

*create code for each substring by using array for each alphabet.

*converting that code to string and map that string using hashmap.

*increment result if a substring's map value contains non zero value.

My code:
 static int sherlockAndAnagrams(String s) {
 HashMap<String,Integer> map = new HashMap<String,Integer>();
 int d,i,k=0;
 int length = s.length();
 int n = length*(length+1)/2;
 String []sub = new String[n];
 for (d = 0; d < length; d++){
     for(i = d+1; i <= length; i++)
      {
        sub[k++] = s.substring(d, i);
      }
  }
int []c = new int[26];

  int result=0;;
for(int l=0;l<n;l++){
    for(int m=0;m<25;m++){
    c[m] = 0;
    }
   char []suba = sub[l].toCharArray();
  for(char ch : suba){
      c[ch-'a']+=1;
  }
  String temp = Arrays.toString(c);
  Integer x = map.get(temp);
  if(x!=null){
      result = result+x;
    map.put(temp,++x);}
  else{
  map.put(temp,1);
   }
  }
  return result;
}

A: Ok, so a couple of things here.

*

*You have to count pairs and not how many collide.

*So, it would be result = result + x;

*Also, map.put(...,x++) should be map.put(...,++x); as we are going to update with a pre-incremented value.

*Also, your filling of c goes from 0 to 24 but it should be 0 to 25. It's a better practice to just do Arrays.fill(c,0) for that matter.

For space efficiency, we can completely avoid taking each subarray in an array and rather just sort the subarray based on characters. This way, every anagram will map to the same key in the map, helping you to avoid storing each array explicitly in the sub string array. However, the overall space complexity would remain the same.


text:
Q: Relative path to absolute with scrapy I'm trying to crawl a forum for ultimately posts in threads that have links posted in them. Right now I'm just trying to scrape the users names of the posts. But I think there is a problem with the urls not being static.
spider.py

from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.item import Item, Field

class TextPostItem(Item):
    title = Field()
    url = Field()
    submitted = Field()

class RedditCrawler(CrawlSpider):
    name = 'post-spider'
    allowed_domains = ['flashback.org']
    start_urls = ['https://www.flashback.org/t2637903']

    def parse(self, response):
        s = Selector(response)
        next_link = s.xpath('//a[@class="smallfont2"]//@href').extract()[0]
        if len(next_link):
            yield self.make_requests_from_url(next_link)
        posts =   Selector(response).xpath('//div[@id="posts"]/div[@class="alignc.p4.post"]')
        for post in posts:
            i = TextPostItem()
            i['title'] = post.xpath('tbody/tr[1]/td/span/text()').extract() [0]
            #i['url'] = post.xpath('div[2]/ul/li[1]/a/@href').extract()[0]
            yield i

Provide me the following error:
raise ValueError('Missing scheme in request url: %s' % self._url)
ValueError: Missing scheme in request url: /t2637903p2

Any idea?

A: You need to "join" the response.url with the relative url you've extracted using urljoin():
from urlparse import urljoin

urljoin(response.url, next_link)

Also note that there is no need to instantiate a Selector object - you can use the response.xpath() shortcut directly:
def parse(self, response):
    next_link = response.xpath('//a[@class="smallfont2"]//@href').extract()[0]
    # ...


text:
Q: Trying to add ImageTexture to a shape of IndexedFaceSet, how can I control the appearance of ImageTexture? I tried to build a cup like can.proto, but the appearance of ImageTexture was strange. How can I control it?

A: It seems the texture mapping of your IndexedFaceSet (https://www.cyberbotics.com/doc/reference/indexedfaceset) node is not defined (or wrongly defined). You can define it using the 'texCoord' field of the IndexedFaceSet node.
The texture mapping defines how each point of the IndexedFaceSet is mapped to the texture. I would recommend reading this: https://www.rigacci.org/docs/biblio/online/vrml/ch15.htm


text:
Q: JVM internal working for join() method in java Simply put, How does the join() method of Thread works internally, I know that using join() method you can join one thread at the end of other.
For example, if we use thread.join() in main thread, then the main thread should wait until run method of Thread thread finishes completely. But how it happens internally, will this append the stack of main thread at the end of thread's stack. I am confused as two threads cannot share the same stack. Please correct me if I am wrong.

A: Here's the implementation from the Oracle JDK (as seen in jdk1.8.0_05/src.zip)
/**
 * Waits at most {@code millis} milliseconds for this thread to
 * die. A timeout of {@code 0} means to wait forever.
 *
 * <p> This implementation uses a loop of {@code this.wait} calls
 * conditioned on {@code this.isAlive}. As a thread terminates the
 * {@code this.notifyAll} method is invoked. It is recommended that
 * applications not use {@code wait}, {@code notify}, or
 * {@code notifyAll} on {@code Thread} instances.
 *
 * @param  millis
 *         the time to wait in milliseconds
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public final synchronized void join(long millis)
throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

As you can see, no fancy stack manipulation occurs. They simply use the wait and notify methods to have one thread wait until the other notifies it of its termination.

A: Each JVM might implement this differently, but I think most (or at least Oracle and openJDK) do end up calling pthread_join.
And how does pthread_join works? There's already a question with that:
How is pthread_join implemented?
I don't think anthing would fiddle with the stack in the way you suggest. As the I linked suggest, it's probably waiting on a semaphore.


text:
Q: Bash if else statement error for (( c=0; c<$i; c++ )); do
if [[ "$aTitle" == "${bookTitle[$c]}" ]]; then
if [[ "$aAuthor" == "${author[$c]}" ]]; then
found=true
fi
fi
done

echo $found

Hi, im pretty new to shell programming, can anyone tell me why I get this error when I run this block of codes? Thanks a lot.
bookTitle & author is an array of strings
aTitle & aAuthor is an input by user
function add_new_book
{
echo "1) add_new_book"

found=false

echo -n "Title: "
read aTitle
echo -n "Author: "
read aAuthor

for (( c=0; c<$i; c++ )); do
    if [[ "$aTitle" == "${bookTitle[$c]}" ]]; then

        if [[ "$aAuthor" == "${author[$c]}" ]]; then

            found=true

        fi

    fi
done

echo $found
}

#author[$i]=$aAut}

./menu.sh: line 43: syntax error near unexpected token `done'
./menu.sh: line 43: `   done'

A: your for loop is wrong for standard posix shell!
It's not C/C++, it's shell and here's the usual way to do it:
for c in $(seq 0 $i); do
    ...
done

and the following construct:
typeset -i i END
for ((i=0;i<END;++i)); do echo $i; done

is bash specific and the following gives no error:
#!/bin/bash

function add_new_book() {
    echo "1) add_new_book"

    found=false

    echo -n "Title: "
    read aTitle
    echo -n "Author: "
    read aAuthor

    # declare c and END as integers
    typeset -i c END
    let END=5 # use END instead of $i if $i is not defined!
    for ((c=0;c<i;++c)); do

        if [[ "$aTitle" == "${bookTitle[$c]}" ]]; then

            if [[ "$aAuthor" == "${author[$c]}" ]]; then

                found=true

            fi

        fi
    done

    echo $found
}

add_new_book

So I guess you may have been trying to run that example with /bin/sh instead of /bin/bash which may be another shell like dash or bsh. Also you shall not use $i in the for loop condition, but i withouth the $.
N.B.: in the script I'm giving, there still is an error: $i is not defined within the context of the script!

A: This example script might be help you more.
bookTitle="linux,c,c++,java"
author="dony,jhone,stuart,mohan"

function add_new_book()
{
    IFS=', '
    read -a bookTitle <<< "$bookTitle"
    read -a author <<< "$author"

    echo "1) add_new_book"

    found=false

    echo -n "Title: "
    read aTitle
    echo -n "Author: "
    read aAuthor

    for index in "${!bookTitle[@]}"
    do
        if [[ "$aTitle" == "${bookTitle[index]}" ]]
        then

            if [[ "$aAuthor" == "${author[index]}" ]]
            then
                    found=true
            fi
        fi
    done

    echo $found
}


text:
Q: Commas from csv only partially imported in Libreoffice Calc I have a CSV here, generated using Rstudio (front-end for R).
When I open it with Libreoffice Calc, the preview in the Text import dialog correctly displays the numbers in the last two columns. There are many numbers with 3 digits after the comma. The last column contains text as well.
When I continue the import, most (not all!) numbers have no comma anymore in Calc. It means the number -2.319 appears as -2319. When I click the cells, I can see in the value field that there really is no comma.
The file is correctly opened by gedit and Google sheets, which display all numbers correctly.
Using tab-delimited CSVs and quotes for text, using another R function to generate the CSV does not change the problem. Even copy-pasting the correctly displayed table from Google sheets into Calc does not help. My only solution is to import the CSV in Google sheets, and export it as ODS.
Any idea how to correctly display the numbers in Libreoffice Calc?

A: Sorry for answering my own question, it was not my intent.
At the same time as sudodus comment was posted, I found out that my locale setting did not use a point as decimal separator. I adapted that and also the Libreoffice language settings to use the point, which resulted in the numbers being displayed correctly.
However, the problem still remains that Calc's text import preview correctly displayed the numbers, and that this did not reflect the numbers display in Calc, hence the confusion. Filed in Bugzilla (114459).


text:
Q: make Jtable non-editable I have a table which is clickable but when I double click, instead of doing what it is told, it goes editing mode. I have tried isCellEditable() method with no success. Maybe I am doing something wrong?
Here is the code:
public AllResultsFromDB(GUI x) {
   final Vector columnNames = new Vector();
   final Vector data = new Vector();

        for (int i = 1; i <= columns; i++) {
            columnNames.addElement(metad.getColumnName(i));
        }

        //  This loop gets the data inside the rows

        while (rset.next()) {
            final Vector row = new Vector(columns);

            for (int i = 1; i <= columns; i++) {
                row.addElement(rset.getObject(i));

            }

            data.addElement(row);
            //data.addElement(b);
        }

        rset.close();
        stmt.close();
        connection.close();

        //  Create table with results

      final JTable  table = new JTable(data, columnNames) {

            public boolean isCellEditable() {
                           return false;
                       }

            public Class getColumnClass(int column) {

                for (int row = 0; row < getRowCount(); row++) {

                    Object obj = getValueAt(row, column);

                    if (obj != null) {

                        return obj.getClass();

                    }
                }

                return Object.class;
            }

        };

        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll);

        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);

        table.addMouseListener(new MouseListener() {

            public void mousePressed(MouseEvent e) {

                //System.out.println(table.getSelectedRow());

            }

            public void mouseReleased(MouseEvent e) {
                //System.out.println(table.getSelectedRow());

            }

            public void mouseEntered(MouseEvent e) {
                //System.out.println(table.getSelectedRow());

            }

            public void mouseExited(MouseEvent e) {
                //System.out.println(table.getSelectedRow());
            }

            public void mouseClicked(MouseEvent e) {

                if(e.getClickCount()==2){

                System.out.println(table.getSelectedRow());
            }

            }
        });

A: The method isCellEditable that you tried to override has a different signature which is:
public boolean isCellEditable(int row, int column)

How could you specify which specific cell otherwise? Next time adding an @Override annotation should help spotting this.
In any case this is not the correct way to make a JTable non-editable. The correct way is to provide a custom AbstractTableModel which returns false with its isCellEditable method. The JTable shouldn't decide if a cell is editable, it's duty of the model to decide it: indeed the isCellEditable method of JTable just asks to its model if the cell is editable. The JTable shows the content, nothing more, it's the model that decides and contains the data.
Since you seem to use just basic features of a JTable you don't need to roll your own table model, a DefaultTableModel will work for you, and you can overrite its isCellEditable method.

A: You're not that far off.
The actual method isCellEditable takes two parameters, so your method isn't actually overriding anything.
See: http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableModel.html#isCellEditable%28int,%20int%29
for the correct method.


text:
Q: Classifying new documents after cross_val_predict I have a sample of approximately 10,000 tweets that I want to classify into the categories "relevant" and "not relevant". I am using Python's scikit-learn for this model. I manually coded 1,000 tweets as "relevant" or "not relevant". Then, I ran a SVM model using 80% of the manually coded data as training data and the rest as test data. I obtained good results (prediction accuracy ~0.90), but to avoid overfitting I decided to use cross-validation on all 1,000 manually coded tweets.
Below is my code after already obtaining the tf-idf matrix for the tweets in my sample. "target" is an array listing whether the tweet was marked as "relevant" or "not relevant".
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict

clf = SGDClassifier()
scores = cross_val_score(clf, X_tfidf, target, cv=10)
predicted = cross_val_predict(clf, X_tfidf, target, cv=10)

With this code, I was able to get predictions of what classes the 1,000 tweets belonged to, and I could compare that against my manual coding.
I'm stuck on what to do next in order to use my model to classify the other ~9,000 tweets that I did not manually code. I was thinking to use cross_val_predict again, but I'm not sure what to put in the third argument since the class is what I'm trying to predict.
Thanks for all your help in advance!

A: cross_val_predict is not method to actually obtain predictions from the model. Cross validation is a technique for model selection/evaluation, no to train model. cross_val_predict is very specific function (which gives you predictions of many models, trained during cross validation procedure). For actual model building yu are supposed to use fit to train your model and predict to get predictions. No cross validation involved here - as said before - this is for model selection (to choose your classifier, hyperparamters etc.) and not to train actual model.


text:
Q: Elements of a vector space are uniquely determined by the vectors of its direct sums? I need help proving that if $V = U \oplus W$, then for every $v \in V$, there exist unique elements $u \in U$ and $w \in W$ such that $v=u+w$.

A: If $u+w=u'+w'$ then $u-u'=w'-w\in U\cap W$ (because the left side of the equality is in $U$ and the right side is in $W$). From here we conclude $u-u'=0=w-w'\implies u=u'$ and $w=w'$ as desired.
This is because $U\cap W=\{0\}$ since the sum is direct.


text:
Q: Exchange data between an sql and javascript I am about to learn sql and I have a question.Is it possible to use jquery(or php) to collect data(and add) from an sql database?
I would like a detailed answer

A: It is possible, but your question is very broad.Check out the tutorials that W3 Schools provide, in my experience these are a great way to get started and provide great tutorials on PHP, SQL and jQuery.


text:
Q: CollectionView items does not update while setting x:DataType to ViewModel in Xamarin Forms I have a CollectionView that has its ItemsSource bound to an ObservableCollection and it works fine. But when I add x:DataType="viewmodels:MyPageViewModel" in the XAML, it does not show any items, even those items that are initialized in the ViewModel's constructor are not shown in the CollectionView. It also does not show updated items.
Here's my XAML Code (MyPage.xaml):
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage ...
             xmlns:viewmodels="clr-namespace:MyProject.ViewModels"
             x:DataType="viewmodels:MyPageViewModel"
             x:Class="MyProject.Views.MyPage">

    <ContentPage.Content>
        <StackLayout>
            <CollectionView ItemsSource="{Binding Strings}">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout>
                            <Label Text="{Binding .}" />
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

            <Button Text="Add More" Command="{Binding AddMoreItemsCommand}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Here I have specified Binding in the C# Code Behind (MyPage.xaml.cs):
BindingContext = new ViewModels.MyPageViewModel();

Here's my ViewModel (MyPageViewModel.cs):
public class MyPageViewModel : INotifyPropertyChanged
{
    public ObservableCollection<string> Strings { get { return strings; } set { strings = value; OnPropertyChanged(nameof(Strings)); } }
    ObservableCollection<string> strings;

    public MyPageViewModel()
    {
        Strings = new ObservableCollection<string> { "1", "2", "3" };
    }

    public ICommand AddMoreItemsCommand => new Command(() =>
    {
        Strings.Add("4");
        Strings.Add("5");
        Strings.Add("6");
    });

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Note that if I remove x:DataType="viewmodels:MyPageViewModel", everything works fine.
Also if I edit something in ColllectionView while the app is running, it renders the items properly as expected through XAML Hot Reload. But it doesn't fulfil the need as it does not work if I rerun the Project again.
Is there a bug in Xamarin Forms, I am running the latest Xamarin.Forms 5.0.0.2515, I have also tried it in Xamarin.Forms 5.0.0.2478? Or am I missing something? any help would be much appreciated.

A: Specify x:DataType="modelOfYourCollection" in <DataTemplate> of the CollectionView.
If you are using any control that has a DataTemplate you must also setup the compiled binding on it. Here, we have a CollectionView that is data bound to an ObservableCollection<string>. We can bring in the System namespace just like we did for the viewmodels:MyPageViewModel because we are using collection of string type and String class resides in System namespace.

*

*Firstly, add namespace in root of the page:

xmlns:sys="clr-namespace:System;assembly=System.Runtime"

*

*And then in your DataTemplate add:

<DataTemplate x:DataType="sys:String">

If we are using our own Custom Model, add model's namespace at the root of the page and then specify model class in DataTemplate of the CollectionView. Note that we have to use Model and not ViewModel in the DataTemplate.
Rest of the code is correct
Final XAML Code will look like:
<ContentPage ...
             xmlns:viewmodels="clr-namespace:MyProject.ViewModels"
             xmlns:models="clr-namespace:MyProject.Models"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime"
             x:DataType="viewmodels:MyPageViewModel"
             x:Class="MyProject.Views.MyPage">
    ...

    <CollectionView ItemsSource="{Binding Strings}">
        <CollectionView.ItemTemplate>
            <DataTemplate x:DataType="sys:String">
                <Label Text="{Binding .}" />
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

    <!-- For collection of your custom model -->

    <CollectionView ItemsSource="{Binding Monkeys}" >
        <CollectionView.ItemTemplate>
            <DataTemplate x:DataType="models:MonkeyModel">
                <Label Text="{Binding MonkeyName}" />
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ContentPage>

Why use Compiled Bindings? Compiled bindings are resolved more quickly than classic bindings. Hence, improves data binding performance in Xamarin.Forms applications.

*

*Refer this blog by James Montemagno for more details.

*Refer here for Xamarin.Forms Compiled Bindings Official Documentation.


text:
Q: Unit testing InitializeComponent() for a partial Class I am new to C# and Unit testing and I have been trying to implement tests for the following constructor:
public Stepup()
{
    InitializeComponent();
}

Stepup is a partial class and inherits an Interface. How does one implement unit test for such a constructor? Also in addition to that, what are some ways to unit test a simple constructor with no parameters?

A: When a constructor runs, certain invariants about the constructed object should be true. You need to specify what those invariants are, and then test that they are true when the constructor finishes executing. The main point here is that you do not test in the internal implementation details of the constructor, only that whatever your specification says is true about the constructed objects is actually true.
For example:
class Circle {
    private readonly double radius;
    public double Radius {
        get {
            Contract.Ensures(Contract.Result<double>() >= 0));
            return this.radius;
        }
    }

    public Circle(double radius) {
        Contract.Requires(radius >= 0);
        this.radius = radius;
    }
}

Here, the invariant after the constructor finishes is that Circle.Radius returns the value for the constructor parameter radius that was passed in. This is the specification, and it can be tested.


text:
Q: Google Analytics Campaign/Source/Medium Not Showing I have a "short URL" MVC website that takes in an identifier and redirects the user to the end resource based on that identifier.
Prior to the redirect I create a web request to Google Analytics (GA) to track which identifiers are commonly used. I would also like to track some more information using campaign/source/medium options in GA but I'm having a tough time getting these to show in the reports - the link I'm using is below (utmac switched out for obvious reasons):
https://www.google-analytics.com/__utm.gif?utmdt=ShortUrl+Redirect&utmp=%2f3f20118&utmac=UA-9999999-99&utmcc=__utma%3d.1675621744.1591667140.64981.1591667140.64981.1591667140.64981.1%3b%2b&utm_source=TestSource&utm_medium=TestMedium&utm_campaign=TestCampaign
I see the hit but it shows with a medium of "(none)" and source of "(direct)" when I'm expecting to see "TestSource" / "TestMedium"... Is it that I'm constructing the URL wrong or a miss in GA setup?
I've also tried putting the utm_source/campaign/medium as part of the utmp address as query string values but no luck: https://www.google-analytics.com/__utm.gif?utmdt=ShortUrl+Redirect&utmr=0&utmp=/3f20118?utm_source=TestSource&utm_medium=TestMedium&utm_campaign=TestName&utmac=UA-9999999-99&utmcc=__utma%3d.29260146.1591743271.10202.1591743271.10202.1591743271.10202.1%3b%2b

A: You have to add utm parameters to the querystring of website URL.


text:
Q: how to call more than 1 batch files in a vbscript? I am using the following code to call a batch file:
dim shell
set shell=createobject("wscript.shell")
shell.run "a.bat D:\a"
set shell=nothing

How do I call more than 1 batch file, so that when the 1st file's execution is over the 2nd file is executed.
as always, I really appreciate any help offered.

A: Below
shell.run "a.bat D:\a"

add another line with another
shell.run "b.bat ...."

Or create a batch file that calls all the other batch files, and call that batch file from your script.

A: Option explicit
Dim oShell
set oShell = Wscript.CreateObject("WScript.Shell")
oShell.Run "RunAs /noprofile /user:Admininistrator ""%comspec% /c 1stcommand && 2ndcommand && 3rdcommand""", 1, false
WScript.Sleep 1000
oShell.Sendkeys "AdmininistratorPassword~"
Wscript.Quit


text:
Q: strcpy assertion error c++ I am a student Just learning c++ so I am sure there are much more efficient ways of doing this; with that said I would really appreciate some help figuring out why my program crashes. I have narrowed it down the a strcpy function that crashes everything and breaks it, which I have commented out and labeled. I have obviously used the strcpy function multiple times in the program with similar parameters, so I don't understand why that specific one crashes. I have tried everything I can think of and really appreciate the help. As of now I have a lot commented out so it should run with the right text file named "bookdb" my text file currently has this in it
Active Learning Approach,Randal Albert,9780763757236,1,650,1,<br>
Technical Communications,John Lannon,9780321899972,2,724,0,

to see the error you will have to un-comment strcpy(bookArray[num_books].author_name, temp_authorName);
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>

enum Genres {HORROR=1, SCIFI, COMEDY, DRAMA, ACTION};

struct Book
{
    char title[100];
    char author_name[50];
    char isbn[14];
    Genres genre;
    int num_pages;
    bool paperback;
};

//Function Declarations
unsigned short ReadBooks(Book * bookArray, unsigned short & num_books);
void DisplayBooks(Book * bookArray, unsigned short num_books);
void ResizeArrays(Book * bookArray, unsigned short num_books);

int main ()
{
    unsigned short num_books = 0;
    Book * bookArray = new Book();

    num_books = ReadBooks(bookArray, num_books);

}//End Main

unsigned short ReadBooks(Book * bookArray, unsigned short & num_books)
{
    ifstream readBooks("bookdb.txt");
    char temp_title[100] = "0";
    char temp_authorName[100] = "0";
    char temp_isbn[14] = "0";

    char temp_genre[50] = "0";
    char temp_numPages[50] = "0";
    char temp_paperback[50] = "0";

    int genreNumber = 0,
        numPages = 0,
        paperback = 0;

    if (readBooks.is_open() )
    {
        cout << "The file was successfully opened\n" << endl;

        readBooks.getline(temp_title, 100, ',');//Reads into temp cstring
        strcpy(bookArray[num_books].title, temp_title); //copies to dynamic cstring
        //cout << bookArray[num_books].title << endl; //displays part of structure to make sure it worked!!

        readBooks.getline(temp_authorName, 100, ',');
        strcpy(bookArray[num_books].author_name, temp_authorName);
        //cout << bookArray[num_books].author_name << endl;

        readBooks.getline(temp_isbn, 14, ',');
        strcpy(bookArray[num_books].isbn, temp_isbn);
        //cout << bookArray[num_books].isbn << endl;

        readBooks.getline(temp_genre, 50, ',');//Get the genre as a char
        genreNumber = atoi(temp_genre);//converts char to an int
        bookArray[num_books].genre = static_cast <Genres> (genreNumber);//converts int to ENUM
        //cout << bookArray[num_books].genre << endl;//Displays ENUM to make sure it worked!!

        readBooks.getline(temp_numPages, 50, ',');
        numPages = atoi(temp_numPages); //converts char to an int
        bookArray[num_books].num_pages = numPages; //assigns int to structure
        //cout << bookArray[num_books].num_pages << endl; //Displays part of structure to make sure to works!!

        readBooks.getline(temp_paperback, 50, ',');
        paperback = atoi(temp_paperback); //converts char to an int
        bookArray[num_books].paperback = static_cast <bool> (paperback);
        //cout << bookArray[num_books].paperback << endl;
        num_books++;

        //DisplayBooks(bookArray, num_books);
        ResizeArrays(bookArray, num_books);
        cout << "The number of books is: " << num_books << endl;

        //while (!readBooks.eof() )
        //{

        readBooks.getline(temp_title, 100, ',');//Reads into temp cstring
        strcpy(bookArray[num_books].title, temp_title); //copies to dynamic cstring
        cout << bookArray[num_books].title << endl; //displays part of structure to make sure it worked!!

        readBooks.getline(temp_authorName, 100, ',');
        cout << temp_authorName << endl;
        //strcpy(bookArray[num_books].author_name, "0");
        ///THIS BREAKS MY CODE////strcpy(bookArray[num_books].author_name, temp_authorName);
        //cout << bookArray[num_books].author_name << endl;

        readBooks.getline(temp_isbn, 14, ',');
        //strcpy(bookArray[num_books].isbn, temp_isbn);
        //cout << bookArray[num_books].isbn << endl;

        readBooks.getline(temp_genre, 50, ',');//Get the genre as a char
        //genreNumber = atoi(temp_genre);//converts char to an int
        //bookArray[num_books].genre = static_cast <Genres> (genreNumber);//converts int to ENUM
        //cout << bookArray[num_books].genre << endl;//Displays ENUM to make sure it worked!!

        readBooks.getline(temp_numPages, 1000, ',');
        //numPages = atoi(temp_numPages); //converts char to an int
        //bookArray[num_books].num_pages = numPages; //assigns int to structure
        //cout << bookArray[num_books].num_pages << endl; //Displays part of structure to make sure to works!!

        readBooks.getline(temp_paperback, 50, ',');
        //paperback = atoi(temp_paperback); //converts char to an int
        //bookArray[num_books].paperback = static_cast <bool> (paperback);
        //cout << bookArray[num_books].paperback << endl;*/

        num_books++;

        //ResizeArrays(bookArray, num_books);
        //}//End while

        readBooks.close();
    }//End if
    else
    {
        cout << "There was not an existing book file, so one will be created"  << endl;
    }//End else

    return 0;
}//End ReadBooks

void DisplayBooks(Book * bookArray, unsigned short num_books)
{
    for (unsigned short i = 0; i < num_books; i++)
    {
        cout << setw(30) << left << bookArray[i].title << left << setw(20) << bookArray[i].author_name << left << setw(15) << bookArray[i].isbn
             << left << setw(3) << bookArray[i].genre  << left<< setw(6) << bookArray[i].num_pages << left << setw(4) << bookArray[i].paperback << endl;
    }//End For
}//ENd Display Function

void ResizeArrays(Book * bookArray, unsigned short num_books)
{
    Book * temp_bookArray = new Book[num_books + 1];

    for (int i = 0; i < num_books; i++)
    {
        strcpy(temp_bookArray[i].title, bookArray[i].title);
        //cout << temp_bookArray[i].title << endl; //For Debugging

        strcpy(temp_bookArray[i].author_name, bookArray[i].author_name);
        //cout << temp_bookArray[i].author_name << endl; //for Debugging

        strcpy(temp_bookArray[i].isbn, bookArray[i].isbn);
        //cout << temp_bookArray[i].isbn << endl;//for debugging

        temp_bookArray[i].genre = bookArray[i].genre;
        //cout << temp_bookArray[i].genre << endl;//for debugging

        temp_bookArray[i].num_pages = bookArray[i].num_pages;
        //cout << temp_bookArray[i].num_pages << endl;// for debugging

        temp_bookArray[i].paperback = bookArray[i].paperback;
        //cout << temp_bookArray[i].paperback << endl; //for debugging

    }//End for

    delete [] bookArray;

    bookArray = temp_bookArray;

    DisplayBooks(bookArray, num_books); //debugging to make sure bookArray is reassigned

}//End Resize Function

A: strlen gets all elements without '\0',so if you have str = "1234";
the str length is 5,(1234 + '\0) but return 4.Strcpy take all 5 elements + '\0' .

A: There are problems with the ResizeArrays:

*

*It allocates new memory for the array, but doesn't return that new array back to the calling function, so that it can adjust its pointers to the new array location.

*Resize probably needs to sizes, the old size, and the new size, and you will only be able to copy the minimum of those numbers of elements.

Just to fix this to the point where it will work, you can do something like:
Book* ResizeArrays(Book * bookArray, unsigned short num_books)
{
    ....
    return bookArray;
}

Then use the function in this way
bookArray = ResizeArrays(bookArray, num_books);

However, as you use an array delete, for your first allocate, you need to use an array allocation in main() as well,
Book * bookArray = new Book[1];

Even though its only allocating one book, it should be done as an array, so it is compatible with the delete [] used in ResizeArrays.
I assume this is a learning exercise.  In normal use of C++ you wouldn't use naked new and delete operators.  Either you would simply use std::vector or similar, or to create an object that will manage the memory, with the new and delete in the constructor and destructor respectively.

A: Problems that I see:
Problem 1
There isn't enough space to hold the ISBN properly. The length of ISBN in your input file is 14 characters long. To hold them in a null terminated string, you need to have an array that can hold 15 or more characters.
As a result, the line
    readBooks.getline(temp_isbn, 14, ',');

will stop reading after 13 characters since it has to use the 14-th character to store '\0'.
Problem 2
This line doesn't look right.
    readBooks.getline(temp_numPages, 1000, ',');

I suspect this was a typo and you meant
    readBooks.getline(temp_numPages, 50, ',');

Problem 3
There are problems with handling of memory in ResizeArray.
void ResizeArrays(Book * bookArray, unsigned short num_books)
{
    Book * temp_bookArray = new Book[num_books + 1];

    // Here, you are deleting the memory that was allocated in `main`.
    // bookArray in the calling function now points to memory that has been
    // deleted here.
    delete [] bookArray;

    // Here, you are changing the value of bookArray but only
    // locally in this function. This assignment doesn't
    // change the value of bookArray in the calling function.
    bookArray = temp_bookArray;

    DisplayBooks(bookArray, num_books); //debugging to make sure bookArray is reassigned

}//End Resize Function

If you change ResizeArray to:
void ResizeArrays(Book*& bookArray, unsigned short num_books)

things will be better.
Problem 4
I see that you have commented out the while loop in ReadBooks. If you decide to bring that loop back to life, you'll have to resize bookArray in each run of the loop.
Suggestion
It will be easier to use an std::vector<Book*> to hold the books instead of allocating memory for arrays of Books.


text:
Q: Springboot can't find resources! (Suddenly stopped working) So the thing is, since I moved my resources (css, images, js) to resources/static folder my stuff started working.
Until I created a new .html page (meant to be dynamic) and pasted in resources/templates. Then all my resources (css, images) stopped working (can't be found) and I can't make it work again.
I'm using SpringBoot + Thymeleaf and the code can be found at GitHub
I couldn't manage to find a solution after 3 hours of searching, that's why I'm here. Thank you, hope you guys can help :/
Edit (some images):
My project structure
The link:
  <link href="css/bootstrap.min.css" rel='stylesheet' type='text/css'/>
  <link href="css/bootstrap.css" rel='stylesheet' type='text/css'/>

What happens (was working before, I didn't change anything in the code of listed images)

A: I'm not sure what happened but after starting deleting/commenting some code I wasn't using anymore I started to get errors and managed to track the next file to "fix" (delete or comment) and after that it worked again.
Looks like something in the application wasn't right and it didn't give me any erros so I had to manually try to find it.
I'll keep updating this thread if I find anything useful related.


text:
Q: Hadoop and Cassandra benchmarking I have built recently a Hadoop - Cloudera cluster and Cassandra cluster with 2 nodes. I would like to make now some benchmarking, collect some data about resource usage.
I've searched a lot and found HiBench and Cassandra stress tool. I don't want to compare with other systems, I would like to mesure my own, but it is difficult to imagine, how can I get real and correct values. Cluster consists of 2 virtual machines, created with KVM. Cassandra is in Docker containers. Hard to interpret, how to analyze this system, without getting false results.

A: Some remarks

Cluster consists of 2 virtual machines, created with KVM

Don't use virtual machines if you want to benchmark performance. Indeed Cassandra performs sequential writes on disk to optimize scan operations. By using virtual machines and shared disks, the benefit of sequential writes is lost because the hypervisor can re-order and dispatch contiguous data on different disk sectors, thus destroying the previous optimization for sequential scans
One alternative is to ensure that you have a dedicated disk for each VM.
If you're not doing performance benchmark, ignore the above comment
Second advice, use real data set e.g. big data set that do not fit into memory so that you can see how each technology behaves. Read this for more details: http://www.nextplatform.com/2016/02/19/the-myth-of-in-memory-computing/

A: You can use yahoo cloud serving benchmark to benchmark your Cassandra cluster. Below is the link to it and the corresponding git repository.
https://research.yahoo.com/news/yahoo-cloud-serving-benchmark/
https://github.com/brianfrankcooper/YCSB
The benchmark is quite flexible and has a lot of parameters that can be changed to fully understand the cluster behavior and properties. However,
one key drawback of this framework is that it uses random data by default.
But, you can tweak the code to use it for your own data and then, it should probably suit your needs.