text:
Q: How to upload to S3 bucket via HTML form? ("SignatureDoesNotMatch" error) I am trying to upload images to an AWS S3 bucket via an HTML form.
<form action="https://s3.amazonaws.com/3dphy-media-dev" method="post" enctype="multipart/form-data">
    <input type="hidden" name="AWSAccessKeyId" value="AKIAI5LGVRB427BQRRTA">
    <input type="hidden" name="acl" value="public-read">
    <input type="hidden" name="key" value="${filename}">
    <input type="hidden" name="policy" value='
    {
        "expiration": "2019-01-26T16:14:30Z",
        "conditions": [
            {"bucket": "3dphy-media-dev"},
            {"key": "${filename}"},
            {"acl": "public-read"}
        ]
    }
    '>
    <input type="hidden" name="signature" value="wml%2FZoIYBqyCHDRSSxwxkf5EvzQ%3D">
    <!--<input type="hidden" name="Content-Type" value="image/jpeg">-->

    File to upload to S3:
    <input name="file" type="file">
    <input type="submit" value="Upload File to S3">
</form>

However submitting the form results in an error "SignatureDoesNotMatch" and a message "The request signature we calculated does not match the signature you provided. Check your key and signing method."
I checked some of the existing questions on the same topic, but their answers didn't solve the issue.
What am I doing wrong?

A: mc tool at https://github.com/minio/mc can be used easily for this purpose as a general purpose tool to generate this.
$ mc share upload --recursive --expire=12h https://s3.amazonaws.com/backup/2007-Mar-2/backup

$ mc share list upload
URL: https://s3.amazonaws.com/backup/2007-Mar-2/backup
Expire: 11 hours 19 minutes 18 seconds
Share: curl https://s3.amazonaws.com/backup -F x-amz-date=20151125T052221Z -F x-amz-signature=7b13a6db1af025c2b3f1e92cd7c10100b3756c98982def74692722305419a806 -F bucket=backup -F policy=eyJleHBpcmF0aW9uIjoiMjAxNS0xMi0wMlQwNToyMjoyMS45NjJaIiwiY29uZGl0aW9ucyI6W1siZXEiLCIkYnVja2V0IiwiYmFja3VwIl0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCIyMDA3LU1hci0yL2JhY2t1cCJdLFsiZXEiLCIkeC1hbXotZGF0ZSIsIjIwMTUxMTI1VDA1MjIyMVoiXSxbImVxIiwiJHgtYW16LWFsZ29yaXRobSIsIkFXUzQtSE1BQy1TSEEyNTYiXSxbImVxIiwiJHgtYW16LWNyZWRlbnRpYWwiLCJBS0lBSTZTTk1VRk9WSUVGT1pKQS8yMDE1MTEyNS91cy1lYXN0LTEvczMvYXdzNF9yZXF1ZXN0Il1dfQ== -F x-amz-algorithm=AWS4-HMAC-SHA256 -F x-amz-credential=AKIAI6SNMUFOVIEFOZJA/20151125/us-east-1/s3/aws4_request -F key=2007-Mar-2/backup<NAME> -F file=@<FILE>

Alternatively with json output
$ mc share list upload --json
{"status":"success","url":"https://s3.amazonaws.com/backup/2007-Mar-2/backup/","share":"curl https://s3.amazonaws.com/backup -F policy=eyJleHBpcmF0aW9uIjoiMjAxNS0xMi0wMlQwNToxNTozNC45MjlaIiwiY29uZGl0aW9ucyI6W1siZXEiLCIkYnVja2V0IiwiYmFja3VwIl0sWyJlcSIsIiRrZXkiLCIyMDA3LU1hci0yL2JhY2t1cC8iXSxbImVxIiwiJHgtYW16LWRhdGUiLCIyMDE1MTEyNVQwNTE1MzRaIl0sWyJlcSIsIiR4LWFtei1hbGdvcml0aG0iLCJBV1M0LUhNQUMtU0hBMjU2Il0sWyJlcSIsIiR4LWFtei1jcmVkZW50aWFsIiwiQUtJQUk2U05NVUZPVklFRk9aSkEvMjAxNTExMjUvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJdXX0= -F x-amz-algorithm=AWS4-HMAC-SHA256 -F x-amz-credential=AKIAI6SNMUFOVIEFOZJA/20151125/us-east-1/s3/aws4_request -F x-amz-date=20151125T051534Z -F x-amz-signature=3523fed9cc9ffed7873411c1401d3fc2926055a88704e2d20dd49b8734a25469 -F bucket=backup -F key=2007-Mar-2/backup/ -F file=@<FILE>","timeLeft":40240153132134}

Additionally we also have https://github.com/minio/minio-js which works in browser which can be directly plugged in your HTML form.


text:
Q: How update all model to empty I have observable model
var viewModel = kendo.observable({
        Car: { number: '', color: '' },
});

I would to update all field for this model.
Now I'm doing it so:
viewModel.set("Car.number", " ");
viewModel.set("Car.color", " ");

I would do it this in loop

A: Solution is create string const model (enum)
NAME_FIELD: {
            NUMBER : nameModel + "number",
            COLOR: nameModel + "color" }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Following the official ORM tutorial and I'm running into an error Just a heads up, I'm new to programming in general so I'm guessing I'm missing something simple. I've been trying to follow the official tutorial here and I'm at the Building Relationships section. It works up to the last session.commit() when it says there is no 'addresses' table. This is what I think the code should be doing;

*

*Address sets up a table.

*metadata.create_all(engine) creates the table in the current session.

*I set up the new user 'jack' including some addresses.

*I try to add 'jack', then commit.

I'm unsure what I'm doing wrong, I'd appreciate any help.
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref

Base = declarative_base()
metadata = MetaData()
engine = create_engine('sqlite:///:memory:', echo=False)

Session = sessionmaker(bind=engine)
session = Session()

users_table = Table('users', metadata,
                    Column('id', Integer, primary_key=True),
                    Column('name', String),
                    Column('fullname', String),
                    Column('password', String)
                    )

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    def __repr__(self):
       return "<User('%s', '%s', '%s')>" % (self.name, self.fullname, self.password)

class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))

    user = relationship(User, backref=backref('addresses', order_by=id))

    def __init__(self, email_address):
        self.email_address = email_address

    def __repr__(self):
        return "<Address('%s')>" % self.email_address

metadata.create_all(engine)

session.add_all([User('jim', 'Jim Gregson', 'secretword'),
                 User('john', 'John Smith', 'password'),
                 User('jane', 'Jane Doe', 'qweasdzxc'),
                 User('bob', 'Bob Johnson', '122765')])

session.commit()

for instance in session.query(User).order_by(User.id): print instance

jack = User('jack', 'Jack Bean', 'gjffdd')
print "jack.addresses: ", jack.addresses
jack.addresses = [Address(email_address='jack@google.com'), Address(email_address='j25@yahoo.com')]
print "jack.addresses: ", jack.addresses
print "jack.addresses[1].user: ", jack.addresses[1].user

session.add(jack)
session.commit()

Error below when 'session.commit()' is called;
sqlalchemy.exc.OperationalError: (OperationalError) no such table: addresses u'INSERT INTO addresses (email_address, user_id) VALUES (?, ?)' ('jack@google.com', 5)

A: The Base object contains it's own metadata instance that it adds more metadata to as your entities are defined. So, when the User class is defined, the Base object realizes this, and adds all of the metadata for the User class to it's own metadata instance (Base.metadata).
In your script, you've created your own metadata instance (metadata = MetaData()), and then later on used that empty metadata to create your tables (metadata.create_all(engine)).
Don't create your own metadata, and use the base one instead:

Base.metadata.create_all(engine)

Edit:
Another note: You probably would have received the same error for the users table, but it seems that you have defined the users table metadata in what I called in my answer the "empty" metadata. You don't need to do this; defining the User table in the way that you've done it (defining the "User" class) is good enough to do everything you did when you said "users_table = Table(...)". You're basically doing the same thing in two ways, and you really only need to do one.


text:
Q: Java Robot and KeyEvent in MATLAB I have a question regarding using robot and keyevent in MATLAB
import java.awt.Robot;
import java.awt.event.KeyEvent;
robot = Robot;
if isequal(eventdata.Key,'return')  % capture enter
  robot.keyPress(KeyEvent.VK_ENTER);
  robot.delay(0.1);
  robot.keyRelease(KeyEvent.VK_ENTER);
end

This block of code performs its function correctly.  However, it create an enter event outside from the form itself.  How do I contain it in the active form or gui only not in other documentation ?

A: I had a similar problem and was able to solve it by setting focus to the desired figure in addition with some "waiting":
figure(myfigureHandle) %set focus to myFigure
pause(1) %wait for a short amount of time
import java.awt.Robot; import java.awt.event.*; SimKey=Robot;... %doing the robot stuff

In your case, the pause-command should only be used, when you are within the if-condition.
Hope that helps!


text:
Q: Ruby Scan method, regex Hi Im trying to parse this string with scan method
test = "Disk/File System/[/dev/mapper/rhel-var (/var)]/MB free=14791, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB free=9451, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/percent full=1.0"

I have to capture the path : /dev/mapper/rhel-var (/var)
and the number on percent full: 1.0
I have tried with many regex but I can get it to work
testa = test.gsub(',', '')
r = testa.scan(/Disk\/File System\/\[((.*))\]\/percent full=([^[:space:]]+)/)
puts r

---Edit---
the string can have multiple ocurrences of of the FS and the percentage:
test = "Disk/File System/[/dev/mapper/rhel-var (/var)]/MB free=14791, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB free=9451, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/percent full=1.0, Disk/File System/[/dev/sda2 (/boot)]/MB total=1974, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB total=10015, Disk/File System/[/dev/mapper/rhel-root (/)]/percent full=61.0, Disk/File System/[/dev/mapper/rhel-var (/var)]/percent full=23.0, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB total=452543, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB free=426145, Disk/File System/[/dev/mapper/rhel-root (/)]/MB total=10015, Disk/File System/[/dev/mapper/rhel-root (/)]/MB free=3717, Disk/File System/[/dev/mapper/rhel-var (/var)]/MB total=20030, Disk/File System/[/dev/sda2 (/boot)]/percent full=9.0, Disk/File System/[/dev/sda2 (/boot)]/MB free=1699, Disk/File System/[/dev/mapper/rhel-home (/home)]/percent full=1.0, Disk/File System/[devtmpfs (/dev)]/MB total=3851, Disk/File System/[devtmpfs (/dev)]/percent full=0.0, Disk/File System/[devtmpfs (/dev)]/MB free=3851"

help please, thanks

A: You can use
/Disk\/File System\/\[([^\]\[]*)\]\/percent full=(\d+(?:\.\d+)?)/

See the Rubular demo (regex101 demo). Details:

*

*Disk\/File System\/\[ - a Disk/File System/[ string

*([^\]\[]*) - Group 1: any zero or more chars other than [ and ], as many as possible

*\]\/percent full= - a ]/percent full= text

*(\d+(?:\.\d+)?) - Group 2: one or more digits and then an optional sequence of a . and one or more digits.

In Ruby:
test = "Disk/File System/[/dev/mapper/rhel-var (/var)]/MB free=14791, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB free=9451, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/percent full=1.0, Disk/File System/[/dev/sda2 (/boot)]/MB total=1974, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB total=10015, Disk/File System/[/dev/mapper/rhel-root (/)]/percent full=61.0, Disk/File System/[/dev/mapper/rhel-var (/var)]/percent full=23.0, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB total=452543, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB free=426145, Disk/File System/[/dev/mapper/rhel-root (/)]/MB total=10015, Disk/File System/[/dev/mapper/rhel-root (/)]/MB free=3717, Disk/File System/[/dev/mapper/rhel-var (/var)]/MB total=20030, Disk/File System/[/dev/sda2 (/boot)]/percent full=9.0, Disk/File System/[/dev/sda2 (/boot)]/MB free=1699, Disk/File System/[/dev/mapper/rhel-home (/home)]/percent full=1.0, Disk/File System/[devtmpfs (/dev)]/MB total=3851, Disk/File System/[devtmpfs (/dev)]/percent full=0.0, Disk/File System/[devtmpfs (/dev)]/MB free=3851"
rx = /Disk\/File System\/\[([^\]\[]*)\]\/percent full=(\d+(?:\.\d+)?)/
puts test.scan(rx)

Output:
[
   ["/dev/mapper/rhel-opt (/opt)", "1.0"],
   ["/dev/mapper/rhel-root (/)", "61.0"],
   ["/dev/mapper/rhel-var (/var)", "23.0"],
   ["/dev/sda2 (/boot)", "9.0"],
   ["/dev/mapper/rhel-home (/home)", "1.0"],
   ["devtmpfs (/dev)", "0.0"]
]

A: I will write the string as follows to clarify its structure.
test = "Disk/File System/[/dev/mapper/rhel-var (/var)]/MB free=14791," +
       "Disk/File System/[/dev/mapper/rhel-home (/home)]/MB free=9451," +
       "Disk/File System/[/dev/mapper/rhel-opt (/opt)]/percent full=1.0," +
       "Disk/File System/[/dev/sda2 (/boot)]/MB total=1974," +
       "Disk/File System/[/dev/mapper/rhel-home (/home)]/MB total=10015, " +
       "Disk/File System/[/dev/mapper/rhel-root (/)]/percent full=61.0," +
       "Disk/File System/[/dev/mapper/rhel-var (/var)]/percent full=23.0, " +
       "Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB total=452543, " +
       "Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB free=426145," +
       "Disk/File System/[/dev/mapper/rhel-root (/)]/MB total=10015," +
       "Disk/File System/[/dev/mapper/rhel-root (/)]/MB free=3717," +
       "Disk/File System/[/dev/mapper/rhel-var (/var)]/MB total=20030," +
       "Disk/File System/[/dev/sda2 (/boot)]/percent full=9.0," +
       "Disk/File System/[/dev/sda2 (/boot)]/MB free=1699," +
       "Disk/File System/[/dev/mapper/rhel-home (/home)]/percent full=1.0, " +
       "Disk/File System/[devtmpfs (/dev)]/MB total=3851, " +
       "Disk/File System/[devtmpfs (/dev)]/percent full=0.0, " +
       "Disk/File System/[devtmpfs (/dev)]/MB free=3851"

I assume you want to extract all pairs of paths and "percent full" values, disregarding paths that are not followed by "percent full".
You may write
r = /\bDisk\/File System\/\[([^\]]+)\]\/percent full=(\d+\.\d)/

test.scan(r)
  #=> [["/dev/mapper/rhel-opt (/opt)", "1.0"],
  #    ["/dev/mapper/rhel-root (/)", "61.0"],
  #    ["/dev/mapper/rhel-var (/var)", "23.0"],
  #    ["/dev/sda2 (/boot)", "9.0"],
  #    ["/dev/mapper/rhel-home (/home)", "1.0"],
  #    ["devtmpfs (/dev)", "0.0"]]

The regular expression can be written in free-spacing mode to make it self-documenting.
r = /
    \b                     # assert a word break
    Disk\/File System\/\[  # match a string
    ([^\]]+)               # match 1 or more chars other than ']',
                           #   saved to capture group 1
    \]\/percent[ ]full=    # match a string
    (\d+\.\d)              # match one or more digits followed by '.', followed
                           #   by one digit, saved to capture group 2
    /x                     # invoke free-spacing regex definition mode

Note that in free-spacing mode the space between percent and full would be stripped out before the expression is parsed if it were not protected in some way. Enclosing the space in a character class, as I have done, is one of several ways of doing that.


text:
Q: URL Rewriting if it is a single post / redirecting post - post type I have a unique kind of question that I've been wrapping my brain around. Google is penalizing us with duplicate content because you can access our single blog posts both by going to:
http://www.domain.com/blog/the-post-slug

as well as :
http://www.domain.com/the-post-slug

The option we really want is:
http://www.domain.com/blog/the-post-slug

and if a user or googlebot happens to goto:
http://www.domain.com/the-post-slug

redirect them to:
http://www.domain.com/blog/the-post-slug

I know this is a particular situation, but we have many custom post types in our system.
So our structure looks like this.
http://www.domain.com/food/pizza
http://www.domain.com/ice-cream/strawberry
http://www.domain.com/fireworks/bottle-rockets

Ideally, what I would like to do is find some kind of filter that logically checks if the post_type is post and redirect:
http://www.domain.com/the-post-slug

to
http://www.domain.com/blog/post-slug

I tried modifying the register_post_type for the post object, and adding with_front => false and adding blog to the slug, but that doesn't work.
I was able to add /blog/%postname%/ to the permalink structure, and I was successfully able to have a decent structure going that was working, but I got stuck on the taxonomies. When I went to a taxonomy page, I had to goto:
http://www.domain.com/blog/the-taxonomy/flavors

and:
http://www.domain.com/the-taxonomy/flavors

was giving me a 404. So even if I can find a way to make the taxonomies work to where I can do:
http://www.domain.com/the-taxonomy/flavors

that would be awesome! As another side note, I also added with_front to the register_taxonomy, but that was not doing anything either. I even hard flushed the rewrites on all the changes I did.
I know this is a lot, but my brain cannot go any further.. lol
TIA!
Any insight on this?

A: First of all set your permalink structure to /%postname%.
After that add a rewrite rule to rewrite all request like example.com/blog/postname to the appropriate query:
add_action('init', 'blog_front');

function blog_front() {
  add_rewrite_rule('^blog/([^/]+)/?','index.php?name=$matches[1]','top');
}

Now you have to prevent the duplicate url, sending a 301 redirect when example.com/postname is requested:
add_action('template_redirect', 'say_hello_to_google');

function say_hello_to_google() {
  if ( is_main_query() && is_single() && ( empty( get_post_type() ) || (get_post_type() === 'post') ) ) {
    if ( strpos( trim( add_query_arg( array() ), '/' ), 'blog' ) !== 0 ) {
      global $post;
      $url = str_replace( $post->post_name, 'blog/' . $post->post_name, get_permalink( $post ) );
      wp_safe_redirect( $url, 301 );
      exit();
    }
  }
}

Finally you have to create permalink for your post with 'blog/' in front:
add_filter('the_permalink', 'post_permalink_w_blog');

function post_permalink_w_blog( $link ) {
  global $post;
  if ( $post->post_type === 'post' ) {
    $link = str_replace( $post->post_name, 'blog/' . $post->post_name, get_permalink( $post ) );
  }
  return $link;
}

Last thing to is flush rewrite rules and... test.

Edit
As @Milo pointed out in comments, all of this can be avoided by setting  permalink structure to /blog/%postname% and then use the param 'rewrite' having 'with_front' to false for all CPTs and all taxonomies.
'rewrite' => array( 'with_front' => false )

The problem is that most times, in a average WP install with a lot of CPT and taxonomies, there are chances that some of them are registred via 3rd party plugins...
in that case if that plugins register the CPTs/taxonomies not using 'with_front' => false it's a problem and the solution posted above is the last chance.
In addiction I have to say that standard categories and tags are registered with 'with_front' = true, so using this alternative method also standard category and tag must be re-registered with with_front param setted to false.


text:
Q: Date Picker In Android (ShowDialog () error) I have searched in many sites for date picker in android, but all sites are providing code which contains showdialog(), and eclipse is mentioning that showDialog is deprecated. So anyone please help me with basic date picker. I'm new to android developing, so please be tolerant. I tried from every sites.
Need to place the basic date picker in one xml. (I don't want to include time and all, date alone will do).
Thanks in Advance
this is my class file
public class PremiumCurator extends  FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    setContentView(R.layout.premiumcurator);

    Button btnDate = (Button)findViewById(R.id.btnDate);

     btnDate.setOnClickListener(new OnClickListener()
     {
        @SuppressLint("NewApi")
            public void onClick(View v)
            {
            daatepopup();

    }
     });

 }

 public void daatepopup()
 {
    Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

    OnDateSetListener mDateSetListener = null;
        //updateDisplay();
  DatePickerDialog d = new DatePickerDialog(this, mDateSetListener,mYear,  mMonth, mDay);
  d.show();

 }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
from the reference of yours above is my code, date picker is populated i can able to choose the date. But whenever i give set i need to save my date values. How to fire the event when i click the set button of the date picker ? please see my code and help me out where to add.

A: I am using this code, and its working fine...
Time currDate = new Time(Time.getCurrentTimezone());
currDate.setToNow();
DatePickerDialog d = new DatePickerDialog(this, datePickerListener,
                         currDate.year,  currDate.month, currDate.monthDay);
d.show();
private DatePickerDialog.OnDateSetListener datePickerListener =
                         new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
    {
        // Do as you need
    }
};

A: Refer to the default android provider date piccker


text:
Q: How to use List in reports i got a requirement in which I want to filter a report of opportunities based on a list of users.
My list of users shuffles frequently. I have created a custom label with users names. So we are modifying this label whenever any member is shuffles from the team.
So, I try to filter opportunities owner with this label. So, I created a formula field to get data from custom label. But I can't filter with values.
Please suggest any better idea to resolve this issue.

A: You could create a formula (return type Checkbox):
CONTAINS($Label.ListOfUsers, Owner.Name)

Which you could then filter in the report:
Owner Matches List equals true


text:
Q: How to search in a mysql database with variables Somebody can login. If he login, the entered password (decoded) will be compared with the right passwort (also decoded)
But if I make
$sql = "SELECT PasswordDecode FROM Userinformations WHERE Username = ".$Username;
    foreach ($pdo->query($sql) as $row) {
        $PasswordDecode = $row["Password decode"];
    }

this error comes:

Warning: Invalid argument supplied for foreach() in ...

I don't understand. If the username is  DumbUsername and I make
$sql = "SELECT PasswordDecode FROM Userinformations WHERE Username = DumbUsername";

No error happend and it works. But if I write the Username in a variable, it dowsn't work. Why?
Please answer.

A: Change your query, use quotes arround variable
  $sql = "SELECT PasswordDecode FROM Userinformations WHERE Username = '$Username'";


text:
Q: MessageEmbed field values may not be empty. Discord.js I am working on a code that sends a random picture from a subreddit, from the weekly top.
But I receive the following error when I am trying to use the command:
(node:25) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.

Code:
client.on("message", async message => {
    if (message.content.toLowerCase() === "!foto") {
        const snekfetch = require('snekfetch');
        try {
            const {
                body
            } = await snekfetch
                .get('https://www.reddit.com/r/gtavcustoms.json?sort=top&t=week')
                .query({
                    limit: 10
                });
            const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
            if (!allowed.length) return message.channel.send('Het lijkt erop dat de nieuwe fotos op zijn, probeer het later nog eens!');
            const randomnumber = Math.floor(Math.random() * allowed.length)
            const embed = new Discord.MessageEmbed()
                .setColor(0x00A2E8)
                .setTitle(allowed[randomnumber].data.title)
                .setDescription("Gepost door: " + allowed[randomnumber].data.author)
                .setImage(allowed[randomnumber].data.url)
                .addField("Overige informatie:", "Likes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
            .setFooter("DaddyCoolNL Official Discord Server")
            message.channel.send(embed)
        } catch (err) {
            return console.log(err);
        }
    }
});

A: This may be a simple fix, but may not work. What you can try is putting it in backticks.
.addField("Overige informatie:", `Likes: ${allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)}`

It also may be due to the allowed array not being complete, or something is off with it.


text: Q: Идентификатор для спецсимволов в HTML5 Мне нужно отредактировать спецсимволы на своей странице, но я не знаю как присвоить им id для дальнейшего редактирования символа в CSS. Каким способом это можно сделать? Например, как это делать с тегами я понимаю, а как со спецсимволами нет. И, если использовать теги div, то будет ли это правильно?


text:
Q: Flatten multidimensional array of numbers recursively Let's say I have an array like this
Array
(
    [0] => 123
    [180] => Array
    (
        [400] => Array
        (
            [0] => 474
            [1] => 395
            [2] => 994
            [3] => 365
        )
    )
    [1] => 144
    [2] => 119
)

I would like to go though this array and generate a one dimensional array that contains all the numbers. In the loop, if we get an array, then the number is the corresponding array key.
I did something like this but it doesn't work:
function flatten_array($data) {
    $result = array();

    foreach ($data as $key => $value) {
        if(is_array($value)) {
            $result[] = $key;
            flatten_array($value);
        } else {
            $result[] = $value;
        }
    }

    return $result;
}

The resulting array I should get should be this one:
$result = Array
(
    [0] => 123
    [1] => 180
    [2] => 400
    [3] => 474
    [4] => 395
    [5] => 994
    [6] => 365
    [7] => 144
    [8] => 119
)

Any help will be appreciated thanks.

A: There are some helpful libraries in composer, for example this one: https://packagist.org/packages/nikic/iter
With this lib you can flatten the data the following way:

$result = toArray(flatten($data));

A: Without using libraries, such result can be achieved this way:
function flattenArray(array $data) {
    $values = array_values($data);
    $result = [];

    foreach ($values as $value) {
        if (is_array($value)) {
            $result = array_merge(flattenArray($value), $result);
        } else {
            $result[] = $value;
        }
    }

    return $result;
}

P.S. Note the mistake in your original example:
$result[] = $key;
flatten_array($value);

You call the recursive function without using its returned result.
And you assign the key instead.

A: Your code doesn't accumulate a result anywhere. You could return arrays and merge them, but to save allocation overhead I recommend using a single result array and passing it by reference into your recursive walk function. Here's a complete example:
function flatten_array($a) {
    function flatten($a, &$flat) {
        foreach ($a as $k => $v) {
            if (is_array($v)) {
                $flat[] = $k;
                flatten($v, $flat);
            }
            else {
                $flat[] = $v;
            }
        }
    }

    $flat = [];
    flatten($a, $flat);
    return $flat;
}

$a = [
    123,
    180 => [
        400 => [
            474,
            395,
            994,
            365,
        ]
    ],
    144,
    119
];

print_r(flatten_array($a));

If you expect your depth to be massive, you can do it iteratively to avoid an overflow. Note that this gives a breadth-first ordering:
function flatten_array($a) {
    $flat = [];

    for ($stack = [$a]; count($stack);) {
        foreach (array_pop($stack) as $k => &$v) {
            if (is_array($v)) {
                $flat[] = $k;
                $stack[] = $v;
            }
            else {
                $flat[] = $v;
            }
        }
    }

    return $flat;
}

A: You can use next recursive function:
function array_flat($arr) {
    $res = [];
    foreach($arr as $key=>$val) {
        if (is_array($val)) {
            // element is array: Push key to result and merge recursion result
            array_push($res, $key);
            $res = array_merge($res, array_flat($val));
        } else {
            // push simple value to result
            array_push($res, $val);
        }

    }
    return $res;
}

print_r(array_flat($arr));

Try working PHP code o PHPize.online


text:
Q: UiCollectionView cells issue I have an collectionview with various cells but I have a problem:
if I execute code on iPhone 6s simulator I get this (I want this on every device):

if I execute it on iPad Retina I get this:

and if I execute it on iPhone 5 (I dont see cells):

How do I solve this problem?
Can you help me?
//UPDATE:
if I remove all object in uicollectionviewcell (in this case only the image view) everything work fine (the cells are the same on iPad, iPhone 5 I see the cell) but naturally in the cell I havent objects

A: Have you tried implementing sizeForItemAtIndexPath to give a width equal to the collection view's width?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.size.width, height: /* your height */)
}


text:
Q: Modify variable in child process #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
 int x = 10;
 pid_t p = fork(), t = fork(), s = fork();
 printf("PID = %d -> pai: %d -> x = %d\n", getpid(), getppid(), x);
 return 0;
}

I'm really new to coding and been trying to do some exercises and there's this one where I can't do it

"The proposed code generates a creation of 8 processes in all, where 7 of them are considered child processes.
Change the formatting code as each of the child processes increases the variable  by 2 (two)
units."

Thanks in advance, even you if just took your time to read it!

A: From the fork() man page:

RETURN VALUE
On success, the PID of the child process is returned in the parent, and 0 is returned in the child.  On failure, -1 is returned in the parent, no child process is created, and errno is set  appropri‐
ately.

Thus, you shoud check in each case wether you're in the parent or the child process, and proceed accordingly.
Hope this helps!


text:
Q: How to focus child item while finger slipping on its parent container like a Linearlayout? I have a LinearLayout which contains some TextView vertically. I have made all TextView focusable.
What I want to do is that when user use finger slip on the LinearLayout from top to Bottom, the focus would change accordingly, the focus should change along with finger movement.
How can I do this?

A: There is no focus when the user's finger is on screen. See http://android-developers.blogspot.com/2008/12/touch-mode.html


text:
Q: jQuery Rateyo rating plugin integration with AngularJS I am trying to integrate the Rateyo plugin with AngularJS and getting problem in defined rating value from directive, following are codes:
EDIT: Here is the working plunker
Controller
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
   $http.get("http://mynahcare.info/frontendapi/hospital_list")
   .then(function (response) {$scope.names = response.data.HospitalList;});
});

Directive
app.directive("rateYo", function() {
    return {
        restrict: "A",
        scope: {
            rating: "="
        },
        template: "

",
        link: function( scope, ele, attrs ) {
            $(ele).rateYo({
                rating: String("{{scope.rating}}"),
                starWidth: "20px",
                ratedFill: "#ffce59",
                readOnly: true
            });
        }
    };
});

And this is the HTML code

 <a href="<?php echo $this->config->item('search_url');?>{{y.hosurl}}">

{{y.clinic_name}}

{{y.rating }} {{y.localty }} {{y.city }}

{{y.clinic_type }}

{{y.hos_time }}

Error in the console is Invalid Rating, expected value between 0 and 5
But if you see the API, the data is in number, can somebody please see what I am doing wrong here?

A:

<!DOCTYPE html>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.2.0/jquery.rateyo.min.css" />

List data

{{y.clinic_name}}

                        <rate-yo rating="y.rating" class="mc-doc-rating"></rate-yo>

{{y.rating }} {{y.localty }} {{y.city }}

{{y.clinic_type }}

{{y.hos_time }}

Make your directive "rateYo" as Element so you can pass value of "rating" through attribute and it can be accessed in directive scope.
Please make following changes to resolve your issue
In directive
app.directive("rateYo", function() {
return {
    restrict: "E",
    scope: {
        rating: "="
    },
    template: "

",
    link: function( scope, ele, attrs ) {
        $(ele).rateYo({
            rating: scope.rating,
            starWidth: "20px",
            ratedFill: "#ffce59",
            readOnly: true
        });
    }
  };
});

In HTML replace

With
<rate-yo rating="y.rating" class="mc-doc-rating"></rate-yo>


text:
Q: Conditional Where Clause Oracle SQL based on procedure input varaible I have a plsql procedure which take an input variable. This variable (my_plsql_var) I need to decide the where clause of my select statement. If my variable is A then I need to query a specific where clause, if it is B it uses that specific where clause and same goes for C.  I have tried some queries but they do not work. The closest I have gotten is this, but there seems to be syntax errors and am even unsure if the query will produce what I need.
SELECT ID,
    CASE(CAST WHEN my_col1 in ('A') and my_col2 = 'A' then 'A GROUP'
                             WHEN my_col1 in ('B') and my_col2 = 'B' then 'B GROUP'
                             WHEN my_col1 in ('C') and my_col2 = 'C' then 'C GROUP'
                             else null
        end as varachar2)) as my_awesome_col
        FROM
        my_table
        WHERE
        id= 100 and
        name = 'Smith' and
        CASE (WHEN my_plsql_var = 'A' then my_col1 in ('A') and my_col2 = 'A'
             WHEN my_plsql_var = 'B' then my_col1 in ('B') and my_col2 = 'B' and my_special_col = 'B'
             WHEN my_plsql_var = 'C' then my_col1 in ('C') and my_col2 = 'C'
        end as varachar2)

A: Can this not just be simplified to this?
SELECT ID,
    my_plsql_var || ' GROUP' AS Group
FROM my_table
WHERE ID = 100
    AND NAME = 'Smith'
    AND (
           (my_plsql_var = 'A' AND my_col1 IN ('A') AND my_col2 = 'A')
        OR (my_plsql_var = 'B' AND my_col1 IN ('B') AND my_col2 = 'B' AND my_special_col = 'B')
        OR (my_plsql_var = 'C' AND my_col1 IN ('C') AND my_col2 = 'C')
    );

A: Your best bet for this is to use dynamic SQL...
Build up your select statement in a string, then use execute immediate to run the query as below.  The code below is untested so might have some syntax errors but should give you an idea of how to do it.  Otherwise Google dynamic SQL.
my_sql_string := 'SELECT ID,
                  CASE(CAST WHEN my_col1 in (''A'') and my_col2 = ''A'' then ''A GROUP''
                       WHEN my_col1 in (''B'') and my_col2 = ''B'' then ''B GROUP''
                       WHEN my_col1 in (''C'') and my_col2 = ''C'' then ''C GROUP''
                       else null
        end as varachar2)) as my_awesome_col
        FROM
        my_table
        WHERE
        id= 100 and
        name = ''Smith'' and ';

 if my_plsql_var = 'A' then
  my_sql_string := my_sql_string || 'my_col1 in (''A'') and my_col2 = ''A''';
 else if my_plsql_var = 'B' then
  my_sql_string := my_sql_string || 'my_col1 in (''B'') and my_col2 = ''B''';
 else if my_plsql_var = 'C' then
  my_sql_string := my_sql_string || my_col1 in (''C'') and my_col2 = ''C''';
 end if;
v_output := execute immediate my_sql_string;

A: You need to evaluate your inputs and build dynamically....
Not certain what you want the procedure to do but this one just opens a ref cursor presumably you would do something with it.
Hope this helps.
    create or replace procedure my_plsql_procedure
    (
        my_plsql_var in varchar2
    )
    is
        dataset sys_refcursor;
        strSql CLOB;
        strPred VARCHAR2(500);
        bAddOtherPred boolean := my_plsql_var = 'B';
    begin
        if bAddOtherPred then
            strPred :=  q'~ and my special_col = 'B' ~';
        else
            strPred := null;
        end if;

        strSql := q'~
            select id,
                   CASE when my_col1 = myCol2 and my_col1 = 'A' THEN 'A GROUP'
                        when my_col1 = myCol2 and my_col1 = 'B' THEN 'B GROUP'
                        when my_col1 = myCol2 and my_col1 = 'C' THEN 'C GROUP'
                        else null end as my_awesome_col
            from my_table
            where my_col1 = my_col2
            and my_col1 = :my_plsql_var
            and id = 100
            and name = 'Smith' ~' || strPred;

        open dataset
        for strSql
        using my_plsql_var;

    end;

A:         Hello you need to build the SELECT Clause dynamically based upon your input. Below is the example for this.

        CREATE OR REPLACE PROCEDURE TEST1_DYN(
        p_in IN VARCHAR2,
        p_ref OUT sys_refcursor )
    AS
      lv_select LONG;
    BEGIN
      lv_select:='SELECT ID,
                  (CASE WHEN my_col1 in ('''||p_in||''')'|| 'and my_col2 = '''||p_in||''''||' then '||''''||p_in||' GROUP'''||
                  ' else null
                  end)  my_awesome_col
                  FROM
                  my_table
                  WHERE
                  id= 100 and
                  name = ''Smith'' and
                  my_plsql_var = '||''''||p_in||''''||' then my_col1 in ('||''''||p_in||''''||') and my_col2 = '||''''||p_in||'''
                  ';
      dbms_output.put_line(lv_select);
OPEN p_ref for lv_select;
    END;


text:
Q: Error5: Access is denied while restarting Event Log service I am trying to restart windows event log service but i get this error
Windows could not stop the windows event log service on local computer.
Error5: Access is deined

My OS is Windows 7 (64) and user type is administrator, and I run service as administrator too.
What is the problem?

A: Regarding the error you got while restarting  windows event log,
Task scheduler  is associate with the windows event log.To restart the windows event log you need to stop the  task scheduler.
Task Scheduler cant be stopped from windows 2008 so there are some steps to disable  the task scheduler for while
For registry entry to disable
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Schedule
and then in the right side there would be start, change its value from 2 to 4
and then you need to  restart the  machine.once it is booted.you can restart the windows event log.
Once done you can re-enable the task schedule by modifying the entries in the registry as 4 and then restart the machine.
Note :Restart is must after changing the registry entries.

A: First of all, make backup up of this folder "c:\windows\system32\winevt".
Check the permissions of this folder, it have to contain full-control for users "eventlog","LOCAL SERVICE" and "LOCAL NETWORK".
After all permission are ok, clear the files in folders and subfolders of winevt.
Reboot system.
Check if service is up or try to start it.


text:
Q: separate one row into multiple based on value in row I am take a data frame similar to this:

GISBLong
GISBLat
B Flyway
B Month
Count of Birds

-85.41667
42.41667
3
6
3

-97.25000
36.0833
2
7
2

And change it into this:

GISBLong
GISBLat
B Flyway
B Month
Bird ID

-85.41667
42.41667
3
6
1.1

-85.41667
42.41667
3
6
1.2

-85.41667
42.41667
3
6
1.3

-97.25000
36.0833
2
7
2.1

-97.25000
36.0833
2
7
2.2

So split the rows by the number in the "Count of Birds". Currently 1 row represents multiple birds and I would like to have 1 row for each bird. Any thoughts or suggestions on a function to use? Thanks so much.

A: You could use dplyr and tidyr. Let df be your data.frame.
library(dplyr)
library(tidyr)

df %>%
  mutate(id=row_number()) %>%
  uncount(Count_of_Birds) %>%
  group_by(id) %>%
  mutate(Bird_ID = paste0(id, ".", row_number())) %>%
  ungroup() %>%
  select(-id)

returns
# A tibble: 5 x 5
  GISBLong GISBLat B_Flyway B_Month Bird_ID
     <dbl>   <dbl>    <dbl>   <dbl> <chr>
1    -85.4    42.4        3       6 1.1
2    -85.4    42.4        3       6 1.2
3    -85.4    42.4        3       6 1.3
4    -97.2    36.1        2       7 2.1
5    -97.2    36.1        2       7 2.2

Data
df <- readr::read_table2("GISBLong  GISBLat     B_Flyway    B_Month     Count_of_Birds
                         -85.41667  42.41667    3   6   3
                         -97.25000  36.0833     2   7   2")


text:
Q: When slide 5 is displayed change slide transition properties on slide 1 I have a presentation that slide 1 .AdvanceOnClick = msoTrue. This is so after the slide show starts, it waits for mouse click before advancing (want slide 1 to display and wait for mouse click).
After the initial mouse click to start advancing, for example on slide 5, I want to change the  .AdvanceOnClick to msoFalse on Slide 1 so the second and subsequent loops auto progress without user intervention. Basically, I want to change the Slide 1 transition properties when the presentation advances to, for example, slide 5.
I have tried the following code, which works fine, but I can't run this code from a different slide;
With ActivePresentation.Slides(1).SlideShowTransition
    .AdvanceOnClick = msoTrue
    .AdvanceOnTime = msoTrue
    .AdvanceTime = 5
End With

A: *

*Set the presentation to loop without the pause after slide 1.

*Create a separate presentation consisting of only slide 1.

*Hyperlink that to slide 2 of the looping presentation.

Now slide 1 will display until you click the hyperlink. Once you click, the presentation will loop without stopping. No VBA required.

A: If you need only one ppt file for some reason then you'll have to use VBA, I believe. This code works just fine only if you use something (a shape) in slide 5 and assign a Mouse Click Action to it to link to slide 1. It doesn't work if you go back to slide 1 using the keyboard arrows or the mouse wheel.
Sub OnSlideShowPageChange(ByVal SSW As SlideShowWindow)
    If SSW.View.CurrentShowPosition = 5 Then
        With ActivePresentation.Slides(1).SlideShowTransition
            .AdvanceOnClick = msoTrue
            .AdvanceOnTime = msoTrue
            .AdvanceTime = 5
        End With
    End If
End Sub


text:
Q: How do I stop a sound in AS3 to play another sound? I have the code
if(_snd !=null)
{
    _channel.stop();
}

_snd = new SoundBeep();
_channel = new SoundChannel();
_channel = _snd.play();

but if the user clicks a few times fast, flash waits a bit, then beeps them fast. I'm not sure what's going wrong. Any ideas?

A: try this:
if(_channel != null)
{
    _channel.stop();
}

_snd = new SoundBeep();
_channel = _snd.play();

A: I had this problem - it was maddening! In other languages (java, C#) I would have used synchronization around a critical section. In Flash I had to fake it. It is not perfect - still a small chance that the second sound will play over the first, but it is very small.
Here is the key: implement a combination of the factory and singleton patterns.
One important discovery I made was that I need to copy my member variable into a temporary variable before I act on it, in case some other call to the object tries to swap in a new Sound before I am finished cleaning up the previous one. Here is a snippet that does that:
    /** Seek into the audio to the given position in milliseconds. */
    public function seek(position:Number, resumePlay:Boolean) {
        trace("--> Seek(" + position + ") " + name);

        var tempAudioChannel:SoundChannel = audioChannel;
        audioChannel = null;
        if (tempAudioChannel != null) {
            tempAudioChannel.stop();
            tempAudioChannel.removeEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
        }
        audioLastPosition = position;

        if (resumePlay) {
            tempAudioChannel = audio.play(audioLastPosition);
            tempAudioChannel.addEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
            audioChannel = tempAudioChannel;
        }
    }

Note how I not only copy from audioChannel to tempAudioChannel, but I have to null out audioChannel until the method is nearly complete, then set its value again. I am safe from synchronization errors during all but the short period between when I test the value of audioChannel and when I have finished the copying and nulling, which should be exceedingly brief.
Back to my comment about the factory and singleton patterns. While one sound is being cleaned up - stopped and discarded - another may be getting started, so I need more than one SoundManager. Thus I create one SoundManager per audio filename. Every time I need to act on an an audio file, the SoundManager class tells me which manager instance to call, so I won't hear duplicates of the same sound started as a result.
The following code is a complete SoundManager from my current commercial project. It references one other class not shown - Configuration, but that class only handles getting paths to audio files from a config file, and getting amplification values from another XML file. (The client supplied files which were not normalized to the same volume level, so we had to do it for them.) So you would have to edit all references to the config object out of this code.
NOTE: I make use of the temporary variable trick ALL OVER THE PLACE, on at least two member variables, audio and audioChannel.
package com.vpg.rns.audio {
    import flash.system.System;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;
    import flash.net.NetStream;
    import flash.net.NetConnection;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.errors.IOError;

    /** Load a Sound from an MP3 file, then hold onto it and mediate playing and disposing of the object, and keep the several Sounds from interfering with one another.
     *  This class stores each SoundManager instance in a collection keyed by the step name.
     *
     *  Do not call the Constructor directly to acquire a SoundManager. Instead, use getInstance.
     */
    public class SoundManager {
        private static var allSounds:Object = new Object();

        public static function getInstance(name:String, config:Configuration) {
            var soundMgr:SoundManager = allSounds[name];
            if (soundMgr == null) {
                soundMgr = new SoundManager(name, config);
                addSoundManager(soundMgr);
            }
            return soundMgr;
        }

        private static function addSoundManager(soundMgr:SoundManager) {
            allSounds[soundMgr.name] = soundMgr;
        }

        private static function removeSoundManager(name) {
            var soundMgr:SoundManager = allSounds[name] as SoundManager;
            allSounds[name] = null;
            if (soundMgr != null) {
                soundMgr.dispose();
            }
        }

        public static function removeAllManagers() {
            var allSoundsTemp:Object = allSounds;
            allSounds = new Object();
            for (var prop:String in allSoundsTemp){
                var soundMgr:SoundManager = allSoundsTemp[prop] as SoundManager;
                if (soundMgr != null) {
                    soundMgr.dispose();
                }
            }
        }

        public static function stopManagers(exceptMgrName:String) {
            for (var prop:String in allSounds){
                var soundMgr:SoundManager = allSounds[prop] as SoundManager;
                if (soundMgr != null && soundMgr.name != exceptMgrName) {
                    soundMgr.stop();
                }
            }
        }

        private var mgrName:String;
        public function get name():String { return mgrName; }

        public var config:Configuration;
        public var audio:Sound;
        public var audioChannel:SoundChannel;
        public var audioLoadStatus:String; // States: no audio, loading, loaded, ready. "loaded" means loaded enough to start playing, but possibly still loading more.

        private var rootPath:String;
        private var dataPath:String;
        private var mediaPath:String;
        public var audioFilename:String;
        private var onLoadHandler:Function; // Called When loading file is complete
        private var onAudioCompleteHandler:Function; // Called When playing audio is complete

        public var duration:Number;
        public var audioLastPosition:Number;

        private var volumeAdjustment:Number;

        /** Construct a SoundManager. Do not call this directy. Use the factory method getInstance instead. */
        function SoundManager(name:String, config:Configuration) {
            mgrName = name;
            this.config = config;
            audioLoadStatus = "no audio";
            duration = 0;
            audioLastPosition = 0;
            volumeAdjustment = 1;
        }

        /*
         * Load the audio, then tigger the loading of the optional cue point xml file, and initialization of the controls.
         *
         * @param rootDirectory ...... Directory containing the config file.
         * @param dataDirectory ...... Directory where cuepoint data is located. Expect the cuepoints file to be in the xml/cuepoints subdirectory.
         * @param mediaDirectory ..... Directory where audio files are located.
         * @param audioFile .......... Name of audio file with extension. Does not include path.
         * @param onLoadHandler ...... Called once the audio is loaded, so the caller can start playing it.
         */
        public function loadAudio(rootDirectory:String, dataDirectory:String, mediaDirectory:String, audioFile:String, onLoadHandler:Function, onAudioCompleteHandler:Function) {
            audioLoadStatus = "loading";
            //Load the audio file.
            this.rootPath = rootDirectory;
            this.dataPath = dataDirectory;
            this.mediaPath = mediaDirectory;
            this.audioFilename = audioFile;
            this.onLoadHandler = onLoadHandler;
            this.onAudioCompleteHandler = onAudioCompleteHandler;
            this.volumeAdjustment = config.getAmplification(this.audioFilename);

            var mySoundReq:URLRequest = new URLRequest(config.osSpecificPath(mediaPath + "/" + audioFilename));

            audio = new Sound();
            audio.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{ trace("SoundLoader.loadAudio ERROR!!!"); trace(e); });
            if (config.platform == "Flash_IDE") {
                audio.addEventListener(Event.COMPLETE, audioReady);
            }
            else {
                // We can't afford to wait for whole audio to load, so wait until some of it is loaded.
                audio.addEventListener(ProgressEvent.PROGRESS, audioProgress1);
                audio.addEventListener(Event.COMPLETE, audioCompletelyLoaded);
            }
            audio.load(mySoundReq);

        }

        // A sufficient portion of the audio has loaded, so start playing.
        private function audioProgress1(evt:ProgressEvent) {
            var loadPercent:Number = Math.round(100 * evt.bytesLoaded / evt.bytesTotal);
            if (loadPercent > 10 && audioLoadStatus == "loading") { //TODO: Deduce a better threshold.
                var audioTemp:Sound = audio;
                audioTemp.removeEventListener(ProgressEvent.PROGRESS, audioProgress1);
                audioTemp.addEventListener(ProgressEvent.PROGRESS, audioProgress2);
                audioLoaded();
            }
        }

        // As the audio continues to load, the duration lengthens, affecting the scrubber thumb position.
        private function audioProgress2(evt:ProgressEvent) {
            var loadPercent:Number = Math.round(100 * evt.bytesLoaded / evt.bytesTotal);
            if (audioLoadStatus == "loading" || audioLoadStatus == "loaded") {
                var audioTemp:Sound = audio;
                if (audioTemp != null) {
                    duration = audioTemp.length / 1000; // Convert from milliseconds to seconds.
                }
            }
        }

        private function audioCompletelyLoaded(evt:Event) {
            var audioTemp:Sound = audio;
            if (audioTemp != null) {
                audioTemp.removeEventListener(Event.COMPLETE, audioCompletelyLoaded);
                audioTemp.removeEventListener(ProgressEvent.PROGRESS, audioProgress1);
                audioTemp.removeEventListener(ProgressEvent.PROGRESS, audioProgress2);
                duration = audioTemp.length / 1000;
            }
        }

        private function audioReady(evt:Event) {
            var audioTemp:Sound = audio;
            if (audioTemp != null) {
                audioTemp.removeEventListener(Event.COMPLETE, audioReady);
                audioLoaded();
            }
        }

        private function audioLoaded() {
            audioLoadStatus = "loaded";

            var audioTemp:Sound = audio;
            if (audioTemp != null) {
                duration = audioTemp.length / 1000; // Convert from milliseconds to seconds.
                var audioChannelTemp:SoundChannel;
                audioChannelTemp = audioTemp.play();
                audioChannelTemp.stop();
                audioChannel = null;
                audioLastPosition = 0;
                audioLoadStatus = "ready";
                onLoadHandler(this);
            }
        }

        public function play() {
            pause();
            trace("--> Play " + name);
            audioChannel = audio.play(audioLastPosition);
            audioChannel.addEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
        }

        /** Seek into the audio to the given position in milliseconds. */
        public function seek(position:Number, resumePlay:Boolean) {
            trace("--> Seek(" + position + ") " + name);

            var tempAudioChannel:SoundChannel = audioChannel;
            audioChannel = null;
            if (tempAudioChannel != null) {
                tempAudioChannel.stop();
                tempAudioChannel.removeEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
            }
            audioLastPosition = position;

            if (resumePlay) {
                tempAudioChannel = audio.play(audioLastPosition);
                tempAudioChannel.addEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
                audioChannel = tempAudioChannel;
            }
        }

        public function pause() {
            trace("--> Pause " + name);
            if (audioChannel != null) {
                audioLastPosition = audioChannel.position;
                audioChannel.stop();
                audioChannel.removeEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
                audioChannel = null;
            }
        }

        public function stop() {
            trace("--> Stop " + name);
            audioLastPosition = 0;
            if (audioChannel != null) {
                audioChannel.stop();
                audioChannel.removeEventListener(Event.SOUND_COMPLETE, onAudioCompleteHandler);
                audioChannel = null;
            }
        }

        /** Elapsed time of audio in seconds. */
        public function get audioElapsed():Number {
            if (audioLoadStatus == "ready") {
                if (audioChannel != null) {
                    return audioChannel.position / 1000.0;
                }
                else {
                    return audioLastPosition / 1000.0;
                }
            }
            else {
                return 0;
            }
        }

        /** Set the audio volume to a number between zero (mute) and one (loud). */
        public function setVolume(volume:Number, soundTransform:SoundTransform = null) {
            if (audioChannel != null) {
                if (soundTransform == null) {
                    soundTransform = new SoundTransform();
                }
                if (volumeAdjustment != 1.0) {
                    trace("setVolume using volume adjustment of " + volumeAdjustment);
                }
                soundTransform.volume = volume * volumeAdjustment;
                audioChannel.soundTransform = soundTransform;
            }
        }

        public function unloadAudio() {
            dispose();
        }

        private function dispose() {
            audioLoadStatus = "no audio";
            var audioTemp:Sound = audio;
            audio = null;
            stop();
            if (audioTemp != null) {
                try {
                    audioTemp.close();
                }
                catch (error:IOError) {
                    trace("Error: Couldn't close audio stream: " + error.message);
                }

            }
        }

    }

}


text:
Q: Tesseract and dylib on OSX Mountain Lion I just installed imagemagick and tesseract through brew, everything went well. When I try tesseract -l eng decrypted.png output, though, I get the following error:
 dyld: Library not loaded: /opt/local/lib/libpng15.15.dylib
  Referenced from: /usr/local/bin/tesseract
  Reason: Incompatible library version: tesseract requires version 32.0.0 or later, but libpng15.15.dylib provides version 29.0.0
Trace/BPT trap: 5

I searched everywhere but I couldn't find any place where it is explained how to update that dynamic library to version 32 (or higher). Any suggestions? Thanks!

A: Done by cleaning my installation of both the softwares and re-installing them through brew. Mind that if there is some linking problem, you have to execute brew link --overwrite tesseract to solve them.


text:
Q: Two divs same CSS? Is it possible to make two divs with the same css, something like:
.Navig1, .Navig11 a {
  display: block;
  height: 15px;
  width: 70px;
  background-color: {color: Navig Bg 1};
  text-align: center;
  font-size: 8px;
  line-height: 15px;
  color: #FFF;
}

Because I don't want my style code to be too long, and I need these two to look the same, but be different when hovered, and I thought this would do, but this code doesn't work.
Where am I making the mistake?

A: Yes it is possible:
.Navig1 a, .Navig11 a {
  display:block;
  height:15px;
  width:70px;
  background-color:#000;
  text-align:center;
  font-size:8px;
  line-height:15px;
  color:#FFF;
}

.Navig1 a:hover {
  /*css property*/
}

.Navig11 a:hover {
  /*other css property*/
}

A: css isn't "programmable". there's no variables or methods to say "use style included in section X here".
but, you can fix it by removing the bgcolor definition from this block and creating a new one
.Navig1, .Navig11 a {
    ... as before ...
}

.Navig1, .Navig11 {
    background-color: #xxx;
}

A: You can do what you want by:
.Navig1, .Navig11 a {
    /* Common Styles */
}

.Navig1:hover {
    /* Navig1 Specific Styles on Hover */
}

.Navig11 a:hover {
    /* Navig1 a Specific Styles on Hover */
}

But, as the other answerers mentioned, you have broken CSS.  What should be going on with the background color?

A: It'll be easier to work out what you are aiming to achieve if you also provide the html. There is no need to have two CSS class's. You can use a single CSS class for the styling multiple elements on a page.
If you have multiple div containers with two set with a class called mynav:

Then one CSS class will effect both.
div.mynav a {
    display: block;
    height: 15px;
    width: 70px;
    text-align: center;
    font-size: 8px;
    line-height: 15px;
    color: #fff;
}

div.mynav a:hover {
    /* new css */
}

If you wish to have a variations then you simply need to create the rule for how the element will change depending on the action you are doing.
Also consider using more than one class for a single element if needs be. Your div could be:

You may find that for what you are doing that some simple Javascript is the best solution.


text:
Q: How to determine the maximum number of threads? I am learning parallel programming. I use OpenMP with C++ and I want to understand how to determine the maximum number of parallel threads I can set on my laptop. In the documentation I found the function omp_get_max_threads(), but how can I make sure the return value is correct?
When I'm compiling this code:
#include <omp.h>
#include <iostream>
using namespace std;
int main()
{
   cout << omp_get_max_threads() << "\n";

#pragma omp parallel
        {

        }
        return 0;

}

Output is: 8
When this:
#include <omp.h>
#include <iostream>
using namespace std;
int main()
{

#pragma omp parallel
        {
            cout << omp_get_max_threads();

        }
        return 0;

}

Output is: 88888888

A: When you want to find out how many threads you are able to use. You can do this by calling std::thread::hardware_concurrency().


text:
Q: Can I get specific metadata from a Func? Consider the following code:
string propertyName;
var dateList = new List<DateTime>() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObject => dateTimeObject.Hour);

// I want the propertyName variable to now contain the string "Hour"

Here is the extension method:
public static string GetPropertyName<T>(this IList<T> list, Func<T, object> func) {
   //TODO: would like to dynamically determine which
   // property is being used in the func function/lambda
}

Is there a way to do this? I thought that maybe this other method, using Expression<Func<T, object>> instead of Func<T, object> would give me more power to find what I need, but I am at a loss at how.
public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
   // interrogate expr to get what I want, if possible
}

This is the first time I have done anything this deep with Linq, so maybe I am missing something obvious. Basically I like the idea of passing in lambdas, so that I get compile-time checking, but I don't know that my idea on how I can use them in this particular case will work.
Thanks

A: here is a very easy and fast way to do it on this blog: http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx

So given:
Func func = Name =>
  "Value";
You can get the lambda parameter
  "Name" from the function delegate by
  calling:
func.Method.GetParameters()[0].Name
  (would return "Name")
Here's the revised Hash method from
  Andrey:

public Dictionary<string, T> Hash<T>(params Func<string, T>[] args)
where T : class
{
    var items = new Dictionary<string, T>();
    foreach (var func in args)
    {
        var item = func(null);
        items.Add(func.Method.GetParameters()[0].Name, item);
    }
    return items;
}

Hope it helps,
Patrick

A: Something like this should do the trick:
public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
  MemberExpression member_expression = expr.Body as MemberExpression;
  if (member_expression == null)
      throw new ArgumentNullException("member_expression");
  MemberInfo member = member_expression.Member;
  PropertyInfo property = member as PropertyInfo;
  string proname = memeber.name;
}

WARNING: Air Code!

A: Just a side note: func.Method.GetParameters()[0].Name is extremelly fast when compared with compiling the lambda and extracting the member expression, then the member info, then the name.

A: This is the version I use, it returns a PropertyInfo, but getting the name is trivial.
public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)
{
    MemberExpression memberExpression = null;

    if (expression.Body.NodeType == ExpressionType.Convert)
    {
        memberExpression = ((UnaryExpression) expression.Body).Operand as MemberExpression;
    }
    else if (expression.Body.NodeType == ExpressionType.MemberAccess)
    {
        memberExpression = expression.Body as MemberExpression;
    }

    if (memberExpression == null)
    {
        throw new ArgumentException("Not a member access", "expression");
    }

    return memberExpression.Member as PropertyInfo;
}


text:
Q: Manage source under git and svn simultanously - does it make sense? This is maybe unusual so let me set the scene:
We have an SVN repo containing our project history - an embedded system based on Linux. The SVN repo contains Linux kernel, U-Boot, busybox etc. sources and all our in-house apps, filesystem and such.
The Linux kernel we have is old and crusty and I am working on porting to the mainline, which is under active development for our platform(s). I am doing the kernel-side work under git and trading patches with "The Community".
I could get things working and take a snapshot of the kernel sources and dump it into SVN, but I'd like to keep the ability to get updates, have local branches and manage patches with git. I could keep two copies of the kernel, one managed by each SCM, but that would be a bit messy. There are also risks of developing and testing using kernel sources managed under git, and forgetting to put those changes into SVN resulting in broken SVN versions where the non-kernel sources are out of sync.
Migrating the entire project to git isn't an option. Managing just the kernel source with git and having a bunch of glue scripts and stored hashes in SVN is possible but it's nicer to have a unified history / diffing ability from SVN for the whole project.
What I'm considering is trying to manage the kernel sources under both SVN and git simultaneously, in the same directory.
As a kernel dev I'd mostly use git and do an SVN commit for internal use when things look good. For other internal users they would be able to get the entire, consistent sources with one SVN checkout, see a unified history, and they could make changes to the kernel sources under SVN. Later I or another git-using person can SVN update to those changes and commit them to git as appropriate.
Some funning around getting git to ignore .svn files and vice versa will have to be done. Also I'm not quite sure how one would take a plain SVN checkout and tell git to start managing the kernel subtree as well, but I'm sure git has some obscure swiss-army-knife options to do it.
So that's my idea du jour. It means most co-workers don't have to worry about git, and we can quietly ignore git and fork away later as needed.
The question here really is, has anyone done something like this, how did it work out, or what alternate solutions did you come up with?

A: I've done this regularly, and it works great.
The only major thing I needed to do was add the .git folder to the subversion ignore list, and the .svn/ folders to the .gitignore file.


text:
Q: vuejs - pass scope templates down multiple child-levels I'm building a table with vue, and I use slots for customized formatting. F.e. the table (which is a component), uses a thead-component, where each th is a scoped/named-slot. Specifing a template for the slot only works from parent to child though (or so it seems - vm.$scopedSlots is empty for the thead-component).
This is the outline of what it looks like:
// in index.html
<my-table :data="data">
  <template name="col1-header" props="column">
    {{ column.name }}
  </template>
</my-table

// in my-table component
<template>

    <my-thead :columns="columns">
    </my-thead>
    // tr: v-for over data

</template>

// in my-thead component
<template>

      <slot :name="column.name + '-header'" :item="column" v-for="column in columns">
        {{ column.name }}
      </slot>

  </thead
</template>

Using the template has no use, since it only seems to apply to my-table rather than my-thead. The only way to use the slots defined in my-thead is if I add templates in the my-table-component, but I need to specify them outside of the component.
Is there a way to pass the template that gets specified when using my-table to the my-thead component? As I already mentioned, I tried using vm.$scopedSlots, but this property is read-only and can't be set on the my-thead component. I can access the $scopedSlots of the parent vm though. I also tried using slot and template in the my-table-component to somehow pass on the template to the child, but that didn't work either.

A: I had to create a github issue for this problem. As per the comments, there are multiple ways of dealing with this:
Pass the slots to the child, by using a render function, as shown below, and setting the scopedSlot property, or by using a property to pass the scopedSlots, as shown here. Or use the in version 2.2.0 added provide/inject mechanisms to set the scopedSlots (which I haven't tried yet).
render (h) {
  return h('child', {
    scopedSlots: this.$scopedSlots
  })
}


text:
Q: I am having trouble removing a custom UIButton from inside a custom UITableViewCell When in editing mode, I want the cell to display a uibutton in addition to the editing accessory. When the tableView goes into editing mode, the button appears fine and works fine. But it never gets removed. I have tried saying myButton.hidden = TRUE in addition to the following code. This is what I have in my custom tableViewCell class
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];

    self.trashButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.trashButton.frame = CGRectMake(337, 17, 27, 30);
    [self.trashButton setBackgroundImage:[UIImage imageNamed:@"trash.png"] forState:UIControlStateNormal];

    if (editing) {
        [self addSubview:self.trashButton];
    } else {

        [self.trashButton removeFromSuperview];
    }
}

A: You are recreating the UIButton every time the setEditing method is called. When you call removeFromSuperview, the button being removed is the one you just created a few lines above, and it's not the one added to your UITableViewCell.
Solution: Make the UIButton a class property, initialize it in initWithFrame or awakeFromNib (if using storyboard), then hide it/show it whenever setEditing is called

A: As I mentioned in my comment above, doing this may be better:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];

    if (self.trashButton)
    {
        [self.trashButton removeFromSuperview];
        self.trashButton = nil;
    }
    else
    {
         self.trashButton = [UIButton buttonWithType:UIButtonTypeCustom];
         self.trashButton.frame = CGRectMake(337, 17, 27, 30);
         [self.trashButton setBackgroundImage:[UIImage imageNamed:@"trash.png"] forState:UIControlStateNormal];

         [self addSubview:self.trashButton];
    }
}


text:
Q: Restful Design - Parent collection object in response when POSTing a resource Let's say we have a collection resource called shelf (of book resources) and we would like to POST a new book:
[POST] /shelves/{shelf-id}/books  [request body -- a book]

I know that the response should be either empty with a reference to the newly created resource (201) or include the created resource (200).
Let's say the clients that are creating book resources, will need to show summary of the shelf the new book is added to. One solution should be making clients to first do a POST (let's call it Req#1 -- to create the new book), and then a GET (Req#2) on the shelf resource to get the summary.
What if we care a lot about efficiency and want to return the result of Req#2 implicitly when getting Req#1 on the server and save one request on the client side? Is it OK based on REST principles to return the parent collection resource information in the response when a resource is added to the collection?
Any alternative design?

A: It's 'OK' for REST design to return different resource states, but HTTP doesn't have a standard way to do this. If you uses the HAL format for you REST api, it does have a way to do embedding, so I suppose you could embed different resources to the response of a POST request.
Note that there's no standard I know of that suggests that the following statement is true: I know that the response should be either empty with a reference to the newly created resource (201) or include the created resource (200).
Anyway, what are you trying to solve? Is it really that expensive to do an extra HTTP request? Where do you base that concern on? What's expensive about it? Is it the latency of having to do an extra roundtrip?
If that's the case, you could consider using HTTP/2 push to push a new version of your parent resource. It's probably the most standards compliant way. If your server and client support this well, then this also means you can use this as a great standard mechanism to push things to clients because they might soon request it.

A:
I know that the response should be either empty with a reference to the newly created resource (201) or include the created resource (200).

This isn't true. According to the spec:

The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code.

In summary, use a 201 status response with information about the new resource. Please don't mix information about other resources with it. That is not RESTful, and apart from pedantry, it probably will make a messy API for very little benefit.


text:
Q: Char.js Interpolation linear i'm trying to draw functions with Chart.js
I have a problem with my draw let's see :
here
This is the 'x' function and the line isn't straight
I don't know if it's a problem of resolution or of interpolation
So here is my chart :
var scatterChart = new Chart(ctx, {
      type: 'line',
      data: {
          datasets: [{
              borderWidth:2,
              pointRadius :0,
              borderColor: 'rgba(0, 0, 255, 1)',
              label: 'Scatter Dataset',
              data: JSON.parse(data),
              fill: false,
              lineTension: 0,
              cubicInterpolationMode: 'linear'

          }]
      },
      options: {
          scales: {
              xAxes: [{
                  type: 'linear',
                  position: 'bottom'
              }]
          },
          pan: {
              enabled: true,
              mode: 'xy'
          },
          zoom: {
              enabled: true,
              mode: 'xy',
          },
          responsive: true,
          maintainAspectRatio: true,
      }
  });

Thx guys

A: The problem is how chart.js is drawing the small line segments between data points.  Here is a fiddle that animates a full opacity line over top of a lighter line.  The second line is growing at a step=1 while the lighter line is nice and straight [{x:-100,y:-100},{x:100,y:100}].  If you change to step=10 you will see the line fill in straight.
In the code below (or in the fiddle) you can play around with changing the borderWidth, borderColor, and opacity.  I tried adding borderCapStyle: 'round' and borderJoinStyle: 'round', but neither seemed to have much effect.
var ctx = document.getElementById("test").getContext("2d");
var i = -100;
var data = [{x: i, y: i}];
var scatterChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      borderWidth: 2,
      pointRadius: 0,
      borderColor: 'rgba(0, 0, 255, 1)',
      label: 'Scatter Dataset 1',
      data: data,
      fill: false,
      lineTension: 0,
      cubicInterpolationMode: 'linear'
    }, {
      borderWidth: 2,
      pointRadius: 0,
      borderColor: 'rgba(0, 0, 255, 0.4)',
      label: 'Scatter Dataset 2',
      data: [{x:-100,y:-100},{x:100,y:100}],
      fill: false,
      lineTension: 0,
      cubicInterpolationMode: 'linear'
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom'
      }]
    },
    pan: {
      enabled: true,
      mode: 'xy'
    },
    zoom: {
      enabled: true,
      mode: 'xy',
    },
    responsive: true,
    maintainAspectRatio: true,
  }
});
var step = 1;
var intervalId = setInterval(function() {
  i += step;
  if (i <= 100) {
    scatterChart.data.datasets[0].data.push({x:i,y:i});
    scatterChart.update();
  } else {
    clearInterval(intervalId);
  }
}, 200);

and
<canvas id="test" width="400" height="300"></canvas>


text:
Q: How to decrease first person shooting camera object in OpenGL I am making 3d open gl project which contain camera object as a shooting bullet but it is render with very big size and contain whole screen in white lines like this

i want to display object  as a center of camera with small size how to do this
code is here
static GLdouble ort1[] = { -200, 200, -33, 140 };
static GLdouble viewer[] = { 525, 25, -180 };
static GLdouble up[] = { 0, 1, 0 };

static GLdouble objec[] = { 525.0, 25, -350 };

    glClear(GL_COLOR_BUFFER_BIT);

        glLoadIdentity();
        gluLookAt(viewer[0], viewer[1], viewer[2], objec[0], objec[1], objec[2], 0, 1, 0);

        glMatrixMode(GL_PROJECTION);
        //glOrtho(-1, 1, -1, 1, -1, 100);
        glLoadIdentity();
        //gluPerspective(fov, 1.333, n, f);
        gluPerspective(fov, 1, 0.001, 1000);
        //gluPerspective(50, screenWidth / screenHeight, 0.000001, 2000);
        glPointSize(2.0);
        glMatrixMode(GL_MODELVIEW);
        //cube.drawFace(10, 20, 10, 22);
        drawFlorr();

        glPushMatrix();
        glTranslatef(viewer[0], viewer[1], viewer[2]); // Translation to the camera center
        glRotatef(camAngle * 57.2957795, 0, 1, 0); // Rotate to correspond to the camera
        //glTranslatef(0.016, 0, -0.05); // Offset to draw the object

        glutWireCone(0.005, 1, 20, 20);
        glPopMatrix();

i am new in game prgramming and stuck in this problem ?

A: You're not setting up the projection matrix correctly.
You need to set the mode to GL_PROJECTION, then set the projection matrix to look at the target (shooter's object of attention) and have a perspective correct with right field of view.
Then set the modelview matrix, mode GL_MODELVIEW.
The gun sight needs to be placed so that it is looking at the camera, and the camera is looking at it. So on the line between the shooter's eyes and his object of attention, perpendicular to it. Do this in the modelview matrix, and call gluLookAt again, on the model.
(Ultimately projection and modelview get multiplied, but Open GL handles that for you).


text:
Q: is possible merge material? I am a newbie. I'm using three to create a Rubik's Cube game, and the problem is that there are too many drawcalls. A 5x5 Rubik's Cube game needs at least 275 drawcalls. which is particularly obvious on phones with poor performance. Is there any way to optimize it?
For example, a cube at the corner of a Rubik's Cube needs 3 faces with colors(see picture flow). This cube needs at last 4 drawcalls. Is there any way to make it only need one drawcall?
Is it possible to merge materials into one so that it only requires one drawcall.
I am not allowed to embed image.
this is image url


text:
Q: wpf : handle itemscontrol child mouse wheel event when mouse focus on child control Need to handle itemscontrol child mouse wheel event when mouse focus on child control.If mouse focus on itemscontrol scroll viewer then that scroll should work.Please help to achieve this.
Note : I am able to route event from child itemscontrol.But inreverse need answer..

A: Add a event for Child Control "PreviewMouseWheel"
private void ChildControl_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            ItemControl.ScrollToVerticalOffset(MainScroll.VerticalOffset - e.Delta);
            e.Handled = true;
        }


text:
Q: Raspberry Pi 400 - Ubuntu 21.04 appears to have broken 2 microSD cards Briefly - tried flashing the 21.04 RPi 400 Desktop image to a 128GB microSD card with the stock Pi Imager on macOS last week. Installed ok, and worked for two reboots, upon which I saw a terminal message on startup telling me the microSD needed a manual fsck running. Did that, but no progress - subsequent restarts took me to the manual fsck message again.
OK, I thought - I'll reflash the SD. However, nothing would complete a reflash (tried Balena Etcher & the Pi imager).
I was also unable to reformat the SD to any file system - tried on macOS Disk Utility, Windows disk management tool, and gparted.
I therefore assumed the SD, despite being less than a year old, was the problem, and ordered a 400GB replacement.
Tried the same process again today, with exactly the same results! I now have two SD cards with a system-boot and a writeable partition, with which I can do nothing.
I'd like to understand how this has happened, but most importantly how I can reformat the SDs so I can use them elsewhere? No tool appears to be able to write to the drive - partitions appear fixed and unalterable. Tried initialising, reflashing, formatting &c.
Errors vary across platforms, but are all to the effect that verification cannot be completed as the contents of the SD cards are different from what was written. I've established that the cards haven't somehow become read-only.
I also used two other SDs in the same reader, with the same Pi 400, and successfully flashed alternative operating systems, and could then reformat the SDs without issue.
It seems as though the Ubuntu image is somehow hosing the cards - has anyone else experienced these issues? I have access to macOS, Windows 10 and several Linux VMs.
TIA,
Darren, UK


text:
Q: How to list docker images with their creation date I would like to list all Docker images on my machine, along with their creation date. Kind of the equivalent of the shell's ls -l.
How to do that?

A: You can use the --format option of the docker image ls command:
docker image ls --format "{{.ID}}: {{.CreatedAt}}"

You can also use .CreatedSince instead of .CreatedAt for relative times.
You can also print repository, tag, digest and size in the same way: https://docs.docker.com/engine/reference/commandline/images/#format-the-output


text:
Q: Multiple databases using repo pattern with ninject and nhibernate I am using the repository/unit of work pattern with nhibernate and ninject. I have a generic repository and the unit of work provides the session factory. It has been working great so far but now I have hit a wall. My project now requires that I have a second database. I cannot wrap my head around how to make my repo/unit of work generic for the databases as well. Here is my code, obtained from here:
Repository:
public interface IRepository<T> where T : class
{
    IQueryable<T> GetAll();
    T GetById(Guid id);
    void Create(T entity);
    void Update(T entity);
    void Delete(Guid id);
}

public class Repository<T> : IRepository<T> where T : class
{
    private UnitOfWork _unitOfWork;
    public Repository(IUnitOfWork unitOfWork)
    {
        _unitOfWork = (UnitOfWork)unitOfWork;
    }

    protected ISession Session { get { return _unitOfWork.Session; } }

    // CRUD operations...
}

Unit of Work:
public interface IUnitOfWork
{
    void BeginTransaction();
    void Commit();
}

public class UnitOfWork : IUnitOfWork
{
    private static readonly ISessionFactory _sessionFactory;
    private ITransaction _transaction;

    public ISession Session { get; private set; }

    static UnitOfWork()
    {
        // Initialise singleton instance of ISessionFactory, static constructors are only executed once during the
        // application lifetime - the first time the UnitOfWork class is used

        _sessionFactory = Fluently.Configure()
                       .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("CONN")))
                       .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("MyAssembly")))
                       .CurrentSessionContext<WebSessionContext>()
                       .BuildSessionFactory();
    }

    public UnitOfWork()
    {
        Session = _sessionFactory.OpenSession();
    }

    public void BeginTransaction()
    {
        _transaction = Session.BeginTransaction();
    }

    public void Commit()
    {
        try
        {
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
        finally
        {
            Session.Close();
        }
    }
}

My only idea is to have separate repository and unit of work classes for each of the databases. This seems really ugly to me as it will be a lot of duplication of code. Is there a way to make the repo/uow generic for the database level as well as the entity type?
My other option that I have seen is that NCommon may be able to handle this for me. I am willing to take that route if that is recommended, but I wasn't ready to jump into bed with it right away as the project has not been updated in over 2 years.

A: Took me a while but here's what I came up with in case anyone else needs this:
Modified Repo:
public interface IRepository<TEntity, TContext> where TEntity : class where TContext : DatabaseContext
{
    IQueryable<TEntity> GetAll();
    TEntity GetById(Guid id);
    void Create(TEntity entity);
    void Update(TEntity entity);
    void Delete(Guid id);
}

public class Repository<TEntity, TContext> : IRepository<TEntity, TContext> where TEntity : class where TContext : DatabaseContext
{
    private UnitOfWork<TContext> _unitOfWork;
    public Repository(IUnitOfWork<TContext> unitOfWork)
    {
        _unitOfWork = (UnitOfWork<TContext>)unitOfWork;
    }

    protected ISession Session { get { return _unitOfWork.Session; } }

    public IQueryable<TEntity> GetAll()
    {
        return Session.Query<TEntity>();
    }

    public TEntity GetById(Guid id)
    {
        return Session.Get<TEntity>(id);
    }

    public void Create(TEntity entity)
    {
        Session.Save(entity);
    }

    public void Update(TEntity entity)
    {
        Session.Update(entity);
    }

    public void Delete(Guid id)
    {
        Session.Delete(Session.Load<TEntity>(id));
    }
}

Modified Unit of Work:
public class UnitOfWork<TContext> : IUnitOfWork<TContext> where TContext : DatabaseContext
{
    private ISessionFactory _sessionFactory;
    private ITransaction _transaction;

    public ISession Session { get; private set; }

    public UnitOfWork(TContext context)
    {
        if (_sessionFactory == null)
        {
            _sessionFactory = context.GetSessionFactory();
        }

        Session = _sessionFactory.OpenSession();

    }

    public void BeginTransaction()
    {
        _transaction = Session.BeginTransaction();
    }

    public void Commit()
    {
        try
        {
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
        finally
        {
            Session.Close();
        }
    }
}

DatabaseContext:
public interface DatabaseContext
{
    ISessionFactory GetSessionFactory();
}

public class QualityControlDatabaseContext : DatabaseContext
{
    public ISessionFactory GetSessionFactory()
    {

        return Fluently.Configure()
                      .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("QCConnection")))
                      .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("QCEntities")))
                      .CurrentSessionContext<WebSessionContext>()
                      .BuildSessionFactory();
    }
}
public class SAPDatabaseContext : DatabaseContext
{
    public ISessionFactory GetSessionFactory()
    {

        return Fluently.Configure()
                      .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("SAPConnection")))
                      .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("SAPEntities")))
                      .CurrentSessionContext<WebSessionContext>()
                      .BuildSessionFactory();
    }
}

A: My solution is the same as Nick but I'm remove from the repository to know which unit of work but instead i use attribute on the Entity to know which unit of work it belong to (i.e. which database). A better solution will be check the Entity mapping but I didn't try it so I don't know if its possible.
the repository interface
public interface IRepository<T> where T : class
{
    Task<object> SaveAsync(T entity, CancellationToken token);

    Task SaveOrUpdateAsync(T entity, CancellationToken token);
    Task<T> LoadAsync(object id, CancellationToken token);
    Task<T> GetAsync(object id, CancellationToken token);
}

the repository implementation - i use Autofac Keyed service. and on the ctor i inject my available unit of work. if no attribute is on the class i assume it's the primary db i need.
public class NHibernateRepository<T> : IRepository<T> where T : class
{
    protected readonly ISession Session;
    private readonly IUnitOfWork _unitOfWork;

    public NHibernateRepository(IIndex<Core.Enum.Database, IUnitOfWork> unitOfWorks)
    {
        var att = typeof(T).GetCustomAttribute<DbAttribute>();
        _unitOfWork = unitOfWorks[att?.Database ?? Core.Enum.Database.System];
        Session = _unitOfWork.Session;
    }

    public Task<T> LoadAsync(object id, CancellationToken token)
    {
        return Session.LoadAsync<T>(id, token);
    }

    public Task<T> GetAsync(object id, CancellationToken token)
    {
        return Session.GetAsync<T>(id, token);
    }

    public IQueryable<T> GetQueryable()
    {
       return Session.Query<T>();
    }

    public Task<object> SaveAsync(T entity, CancellationToken token)
    {
        _unitOfWork.FlagCommit();
        return Session.SaveAsync(entity, token);
    }

    public Task SaveOrUpdateAsync(T entity, CancellationToken token)
    {
        _unitOfWork.FlagCommit();
        return Session.SaveOrUpdateAsync(entity, token);
    }
}

the configuration of the autofac is :
builder.RegisterType<UnitOfWorkFactoryMain>().SingleInstance();
        builder.RegisterType<UnitOfWorkFactorySecondary>().SingleInstance();

        builder.Register(c => new UnitOfWork(c.Resolve<UnitOfWorkFactoryMain>()))
            .Keyed<IUnitOfWork>(Database.System).InstancePerLifetimeScope();
        builder.Register(c => new UnitOfWork(c.Resolve<UnitOfWorkFactorySecondary>()))
            .Keyed<IUnitOfWork>(Database.Secondary).InstancePerLifetimeScope();

the rest is like Nick answer


text:
Q: Internet Explorer do not open php-file (can not find) I have a simple login formular on my website to login to the next site using ajax:
    <form id="formlogin" method="post" action="login.php" role="login">

            <input id="user" type="username" name="username" required class="form-control" placeholder="Enter username" />

            <input type="password" name="password" required class="form-control" placeholder="Enter password" />

        <button type="submit" name="go" class="btn btn-primary btn-block">Login Now</button>
    </form>

this is my ajax code:
$("#formlogin").submit(function() {
    user = $("#user").val();
    sessionID = $("#user").val() + getDateTime();
    time = getTime();
    logindate = getDate();
    timeStamp = getTimeStamp();

    sessionData.sessionID = sessionID;
    sessionData.loginTime = time;
    sessionData.loginDate = logindate;
    sessionData.user = user;
    sessionData.timeStamp = timeStamp;

    var sessionIDJSON = JSON.stringify(sessionData);
    Cookies.set('user', sessionData, {expires: 3, path: 'Main.html'});
});

It used to work before I didnt use bootstrap, but I am pretty sure, that it is not the reason.
Other Browsers (chrome,firefox) work fine except IE.
Internet Explorer tells me that there is an error of opening the login.php file. Right after logging in it seems like it is going to login, but jumps back. And the webdevtool tells me the error.
Maybe someone had the same experience with it. Thanks in advance


text:
Q: Disable tabs in child grid doesn't work correctly ( Kendo-UI ) When I use this code to disable 2nd and 3rd tab in each detailed row (child grid) I see that only the first expanded row and the rows before it have tabs disabled - and all other rows below have enabled tabs - what am I doing wrong?
Tried to put this code both inside and outside function detailInit(e) {}
var tabStrip = $("#mytabstrip").kendoTabStrip().data("kendoTabStrip");
        tabStrip.disable(tabStrip.tabGroup.children().eq(1));
        tabStrip.disable(tabStrip.tabGroup.children().eq(2));

A: There are two things that make an impression in the provided code:

*

*The TabStrip ID is the same for all detail templates. Duplicate IDs are not allwed by web standards and lead to inability to obtain reference to the respective elements, except the first one. Do not use IDs in the detail template at all, or make them inique by using (concatenating) the ID of the master data item. http://demos.telerik.com/kendo-ui/grid/detailtemplate

*Make sure the TabStrip for each detail template is initialized only once. http://docs.telerik.com/kendo-ui/intro/installation/jquery-initialization#duplicate-initialization

A: Thanks @dimodi it's a useful info, I've checked my code and changed refers to class instead of ID's, checked that no duplicate initialization occur - but it didn't help. Than I spotted that in the example they use detailRow.find. Now when using "detailRow.find" each row will have identical behavior. Thanks again and have a nice day!!!
function detailInit(e) {

        var detailRow = e.detailRow;

        detailRow.find(".tabstrip")
            .kendoTabStrip({
                animation: {
                    open: { effects: "fadeIn" }
                },

            });

        tabStrip = detailRow.find(".tabstrip").kendoTabStrip().data("kendoTabStrip");

        tabStrip.disable(tabStrip.tabGroup.children().eq(1));
        tabStrip.disable(tabStrip.tabGroup.children().eq(2));


text:
Q: Is rsync more robust than scp for connection reset? On a big corporate firewall-ridden network, we have traditionally used scp to copy a few brand new files over from one machine to another, as part of the log-file rotation and analysis routine.
However, it has recently been observed that the scp seems to fail randomly, with the Connection reset by peer error message, and our routines break.
Would it be a good idea to switch to rsync in place of scp, or is there a way to make scp a little bit more persistent in trying to copy the files over?

A: "Connection reset by peer" means that the remote end of the TCP stream (not the end which logged the error) closed the TCP stream unexpectedly. This can happen if the program on the remote end has crashed or been killed, for example. The error can also be induced by some network devices--like stateful firewalls or NAT devices--interfering with the TCP stream.
In the best case, whatever is causing the error could be specific to the scp program. Rsync doesn't use scp so it might be unaffected. Alternately, the problem could be generic to ssh connections between the two servers, or even to any TCP stream between the two servers. You'd probably be running rsync through ssh, so it might experience the same problem you're having with scp.
One of the main features of rsync is that, when a destination file already exists but has different contents than the source, rsync doesn't need to retransmit the entire file--it just needs to transmit the additional data to make the destination match the source. When you run rsync and it fails before it finishes, you can restart rsync and it'll pick up where it left off, rather than start over. If you find that rsync is crashing on you like scp has been, then this rsync feature will be extremely valuable.
Rsync will not actually try to reconnect on its own, but you can keep running rsync until it reports success. For example, this bash shell command would do it:
until rsync ...
do
    echo Retrying rsync
done


text:
Q: UWP OAuth google c++ I was trying to write an UWP App in c++ (Visual Studio) for OAuth in to Google Drive API.
I referred the notes from this project under Github -
https://github.com/googlesamples/oauth-apps-for-windows/blob/master/OAuthUniversalApp/README.md
I was able to get the Authorization code from Google. But when I used the Authorization code to request for Authorization token then it is throwing me an error 404.
My Authorization token request URI looks like this -
https://googleapis.com/oauth2/v4/token?code=XXXXXXX#&client_id=ZZZZZZ&client_secret=YYYYYY&redirect_uri=uwapp.testgoogleoauth:/oauth2redirect&grant_type=authorization_code
Going by the notes mentioned in the link, I created the client ID using iOS application type. But I didnt get the client secret key at that step. I had to explicitly generate the client secret key again for the iOS application type.
Is there any issue which you see in the request URI being sent for the Authorization token request? What should be the value of client_secret to be used if the type of client has been selected as iOS in google console?
Thanks,
/vikas

A:
Is there any issue which you see in the request URI being sent for the Authorization token request?

In you request URI you are using https://googleapis.com/oauth2/v4/token. However to make the token request, the correct token endpoint should be:

https://www.googleapis.com/oauth2/v4/token

And this is the reason why you get 404 (Not Found) error.

What should be the value of client_secret to be used if the type of client has been selected as iOS in google console?

In Handling the response and exchanging the code, we can find that

client_secret The client secret you obtained from the API Console (not applicable for clients registered as Android, iOS or Chrome applications).

So for iOS clients, there is no need to use client_secret. And as UWP is similar to iOS, we can also ignore this field in UWP.
The complete authorization token request might look like the following:
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=XXXXXX&
client_id=ZZZZZZ&
redirect_uri=uwapp.testgoogleoauth:/oauth2redirect&
grant_type=authorization_code