text:
Q: Fastest way to skip lines while parsing files in Ruby? I tried searching for this, but couldn't find much. It seems like something that's probably been asked before (many times?), so I apologize if that's the case.
I was wondering what the fastest way to parse certain parts of a file in Ruby would be. For example, suppose I know the information I want for a particular function is between lines 500 and 600 of, say, a 1000 line file. (obviously this kind of question is geared toward much large files, I'm just using those smaller numbers for the sake of example), since I know it won't be in the first half, is there a quick way of disregarding that information?
Currently I'm using something along the lines of:
while  buffer = file_in.gets and file_in.lineno <600
  next unless file_in.lineno > 500
  if buffer.chomp!.include? some_string
    do_func_whatever
  end
end

It works, but I just can't help but think it could work better.
I'm very new to Ruby and am interested in learning new ways of doing things in it.

A: file.lines.drop(500).take(100) # will get you lines 501-600

Generally, you can't avoid reading file from the start until the line you are interested in, as each line can be of different length. The one thing you can avoid, though, is loading whole file into a big array. Just read line by line, counting, and discard them until you reach what you look for. Pretty much like your own example. You can just make it more Rubyish.
PS. the Tin Man's comment made me do some experimenting. While I didn't find any reason why would drop load whole file, there is indeed a problem: drop returns the rest of the file in an array. Here's a way this could be avoided:
file.lines.select.with_index{|l,i| (501..600) === i}

PS2: Doh, above code, while not making a huge array, iterates through the whole file, even the lines below 600. :( Here's a third version:
enum = file.lines
500.times{enum.next} # skip 500
enum.take(100) # take the next 100

or, if you prefer FP:
file.lines.tap{|enum| 500.times{enum.next}}.take(100)

Anyway, the good point of this monologue is that you can learn multiple ways to iterate a file. ;)

A: I don't know if there is an equivalent way of doing this for lines, but you can use seek or the offset argument on an IO object to "skip" bytes.
See IO#seek, or see IO#open for information on the offset argument.

A: Sounds like rio might be of help here. It provides you with a lines() method.

A: You can use IO#readlines, that returns an array with all the lines
IO.readlines(file_in)[500..600].each do |line|
  #line is each line in the file (including the last \n)
  #stuff
end

or
f = File.new(file_in)
f.readlines[500..600].each do |line|
  #line is each line in the file (including the last \n)
  #stuff
end


text:
Q: JPA/Glassfish: persistence.xml ignored? I currently have kind of a problem.
I have a small project defining a Bean and implementing this furthermore the project contains some model schemes for hibernate.
The Bean implementation looks something like this:
 public class TestBean implements TBean {

    @PersistenceContext
    protected EntityManager em;

    public TestBean() {
    }

    public void createEntries(User user) {
           em.persist(user);
       }
 }

I think that this should work fine.
My problem now is, that I did some changes in my persistence.xml but all this changes seem to be ignored. I even deleted the whole content of the persistence.xml and changed the text in it to complete nonsense - nothing changes. My question now is, if glassfish caches the persistence.xml somehow and if yes how can I avoid this caching, and if now - what am I doing wrong ??
Thank you very much :)

A: Check the artifact you're deploying: Open the actual jar file in an archiving program and verify that the file is present in META-INF/ folder (if you're deploying an EJB module) or in WEB-INF/classes/META-INF/ (in case of .war).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linux kernel fatal exception (alignment trap) I am trying to get into kernel programming a bit. I would like to try and print out processes in run queues on each CPU when a specific kernel panic occurs. I have been looking at various code chunks in kernel and tried to emulate the same in my own fashion, but I guess I made some kind of Frankenstein that results in fatal exception and alignment trap:
int cpu = 0;
struct rq *rq;
struct task_struct *p, *n;

for_each_possible_cpu(cpu) {
    rq = cpu_rq(cpu);
    raw_spin_lock(&rq->lock);
    printk(KERN_INFO, "rq->nr_running=%u\n", nr_running);
    list_for_each_entry_safe(p, n, &rq->cfs_tasks, se.group_node) {
        printk(KERN_INFO, "%d : %s\n", p->pid, p->comm);
    }
    raw_spin_unlock(&rq->lock);
};

The loop executes for only CPU 0, and then it goes crazy. Can you point me in the right direction? (This is code I wrote in core.c)
Edit: The problem is in the spinlock. I would guess that only process being run on that CPU can take a lock?
Edit2: It seems I got it to work. I think the problem was that, in the original source code, struct rq* rq declaration was inside the for loop.


text:
Q: Jenkins SSL certificate from Windows AD CS I am trying to configure Jenkins on Windows with a SLL certificate following these instructions. Instead of using a Digicert certificate, our IT administrator would like to generate a certificate using the Windows AD CS using the certificate snap-in of mmc.
However we cannot figure out how to import the keytool generated csr certificate request into the certificate snap-in.
If I use a certificate with a recreated certificate request in the mmc certificate store, the certificate is rejected with the following message:
keytool -importcert -alias jenkins -file "D:\Temp\jenkins\jenkins.pem" -keystore "D:\Temp\jenkins\jenkins.jks"
Enter keystore password:
keytool error: java.lang.Exception: Certificate reply does not contain public key for <jenkins>

Does anyone know how to create an SSL certificate from the Windows certificate store based on a java keytool created csr certificate request?

A: I was able to get Jenkins running with SSL and this is what I did.
On the Jenkins Master

*

*In the Certificate Snap-in of mmc, navigate to Certificates (Local
Computer) / Personal.

*Right click Personal Folder and select All Tasks / Request New
Certificate...

*Confirm the next two Enrollment pages by clicking on Next.

*Check a Webserver Active Directory Enrollment Policy.

*A Warning Message shows below the Enrollment Policy

More information is required to enroll for this certificate. Click here
  to configure settings.

Click on it.

*Fill out the Certificate Properties: Subject name: Common name:
[the name of your jenkins server] Alternative name: DNS: [the
name of your jenkins server] Alternative name: DNS: [the full
name of your jenkins server including your domain]Confirm the
page with OK and the following two pages.

*Export the Certificate as PFX format Right click on
certificate All Tasks / Export...

*Check: Yes, export the private key Check Include all
certificates in the certification path if possible Check:
Export all extended properties Since we are exporting the
private key, we must provide a password Check: Password and
enter your password and password confirmation

*Pick a path for your PFX certificate and finish the export.

*Export the certificate one more time without a password in the
 Base-64 encoded X.509 (.CER) format.

*Rename the resulting .CER file into .PEM.

*Create a java key store on the Jenkins server with
keytool -genkeypair -keysize 2048 -keyalg RSA -alias jenkins -keystore jenkins.jks

*Answer the questions appropriate for your company and organisation.

*Import the PFX certificate into the java keystore with
keytool -importkeystore -srckeystore jenkins.pfx -srcstoretype pkcs12 -destkeystore jenkins.jks -deststoretype JKS

*Copy the jenkins.jks to secrets directory where Jenkins is
 installed (in my case C:\Program Files (x86)\Jenkins\secrets).

*Add the certificate to the Jenkins startup parameters:
 -Djavax.net.ssl.trustStore=%JENKINS_HOME%\secrets\jenkins.jks
 -Djavax.net.ssl.trustStorePassword=[your password for the java key store]

*Restart the jenkins service
On the Jenkins Agent

*Import the PEM certificate from above into the java keystore from the command line with administrator priviliges:
keytool -import -alias jenkins -keystore "C:\Program Files (x86)\Java\jre1.8.0_161\lib\security\cacerts" -file [your pem file]

Enter the password of the keystore (by
 default     changeit) Trust  this certificate? [no]: yes

*Make sure your jenkins-slave.xml in %JENKINS_HOME% does not contain
-noCheckCertificate in the arguments.

*Restart the service jenkinsslave-D__Jenkins.

A: I am reading the tutorial you have mentioned in your post. And I see this sentence:
"if making your own certificate skip steps 3, 4, and 5". Your code seems to be the specified in step 5.
You could try to copy the keystore file to your Jenkins secrets directory as mentioned in step 6.
This link can also be helpful.


text:
Q: how to chain multiple operations in js ternary operator in this case how to chain two operations if expression is true
a = 96
c = 0
a > 50 ? c += 1 && console.log('passed') : console.log('try more')

I tried chaining with && and it worked somehow in react, but not in node with vanilla js

A: Use the comma operator, and use parentheses to make sure everything is grouped.

a = 96
c = 0
a > 50 ? (c += 1, console.log('passed')) : console.log('try more')

A: if-else is preferred:

a = 96
c = 0
a > 50 ? (c += 1) ? console.log('passed') : console.log('try more') : console.log('try more')

a = 46
c = 0
a > 50 ? (c += 1) ? console.log('passed') : console.log('try more') : console.log('try more')

a = 96
c = -1
a > 50 ? (c += 1) ? console.log('passed') : console.log('try more') : console.log('try more')


text:
Q: Find a CFG for all words that can be obtained in the form $a^ib^{i+k}a^k$ Find a CFG for all words that can be obtained in the form of $a^ib^{i+k}a^k$ where $i,k\ge1$.
This is what I have so far:
$$ S\to aXa \\X\to bXB \mid bb  $$
I understand that number of b's must be equal to the addition of the a's on their left and right side.
How do I approach this problem?

A: Writing as $a^ib^ib^ka^k$ makes the rules obvious:
$$S\to XY,X\to aXb|ab,Y\to bYa|ba$$


text:
Q: UnboundLocalError when checking lists of sprite collisions in Pygame I am trying to write a function in pygame that handles collisions in a tile based rpg.
def player_collisions(sprite, group, dir):
    hits_walls = pg.sprite.spritecollide(sprite, group[0], False, collide_hit_rect)
    hits_obj = pg.sprite.spritecollide(sprite, group[1], False, collide_hit_rect)
    inrect = pg.sprite.spritecollide(sprite, group[2], False, collide_hit_rect)
    try:
        if inrect:
            hits_ang = pg.sprite.spritecollide(sprite, group[2], False, pg.sprite.collide_mask)
    except: pass

    if dir == "x":
        if hits_walls:
            sprite.vel.x = 0
            if hits_walls[0].rect.centerx > sprite.hit_rect.centerx:
                sprite.pos.x = hits_walls[0].rect.left - sprite.hit_rect.width / 2
            if hits_walls[0].rect.centerx < sprite.hit_rect.centerx:
                sprite.pos.x = hits_walls[0].rect.right + sprite.hit_rect.width / 2
            sprite.hit_rect.centerx = sprite.pos.x

        if hits_obj:
            sprite.vel.x = 0
            if hits_obj[0].rect.centerx > sprite.hit_rect.centerx:
                sprite.pos.x = hits_obj[0].rect.left - sprite.hit_rect.width / 2
            if hits_obj[0].rect.centerx < sprite.hit_rect.centerx:
                sprite.pos.x = hits_obj[0].rect.right + sprite.hit_rect.width / 2
            sprite.hit_rect.centerx = sprite.pos.x

    if dir == "y":
        if hits_walls:
            sprite.vel.y = 0
            if hits_walls[0].rect.centery > sprite.hit_rect.centery:
                sprite.pos.y = hits_walls[0].rect.top - sprite.hit_rect.height / 2
            if hits_walls[0].rect.centery < sprite.hit_rect.centery:
                sprite.pos.y = hits_walls[0].rect.bottom + sprite.hit_rect.height / 2
            sprite.hit_rect.centery = sprite.pos.y

        if hits_obj:
            sprite.vel.y = 0
            if hits_obj[0].rect.centery > sprite.hit_rect.centery:
                sprite.pos.y = hits_obj[0].rect.top - sprite.hit_rect.height / 2
            if hits_obj[0].rect.centery < sprite.hit_rect.centery:
                sprite.pos.y = hits_obj[0].rect.bottom + sprite.hit_rect.height / 2
            sprite.hit_rect.centery = sprite.pos.y

    if hits_ang:
        sprite.slide_allow = True
        if hits_walls or hits_obj:
            sprite.slide_allow = False

hits_walls and hits_obj store walls and objects the player collides with. hits_ang stores pixel perfect collisions with angled walls and only loads when the player is inside the rectangle that surrounds the wall from point to point.
However, I keep having this error flag up everytime my program runs and reaches the if hits_ang: line.
UnboundLocalError: local variable 'hits_ang' referenced before assignment
All I need is for the program to check if the list hits_ang exists at all, so I don't understand why this line is being rejected when the program is fine with checking for the other 3 collision groups.

A: The variable hits_ang is not always defined as the execution progresses.  It is only defined at the top:
inrect = pg.sprite.spritecollide(sprite, group[2], False, collide_hit_rect)
try:
    if inrect:
        hits_ang = pg.sprite.spritecollide(sprite, group[2], False, pg.sprite.collide_mask)
except:
    pass

So if inrect is False, None, or zero, hits_ang never exists.
An easy way to fix this is to simply default hits_ang to False:
try:
    hits_ang = False
    if inrect:
        hits_ang = pg.sprite.spritecollide(sprite, group[2], False, pg.sprite.collide_mask)
except:
    pass


text:
Q: How to get the number of unread messages and the last message for each user in a SQL query? I have a message table like this:
message_id | body         | from_user_id | to_user_id | is_read | sent_date
---------------------------------------------------------------------------
1          | hello        | 23           | 31         | false   | 2 min ago
---------------------------------------------------------------------------
2          | thank you    | 28           | 31         | true    | 4 min ago
---------------------------------------------------------------------------
3          | how are you? | 31           | 28         | false   | 1 min ago
---------------------------------------------------------------------------
4          | a-ha         | 29           | 31         | false   | 6 min ago

I want to get the number of unread messages and the last message for the current user (for example user_id 31)
desired result:
from_user_id | to_user_id | body         | sent_date | unread_message_count
-------------------------------------------------------------------
23           | 31         | hello        | 2 min ago | 1
-------------------------------------------------------------------
31           | 28         | how are you? | 1 min ago | 0
-------------------------------------------------------------------
29           | 31         | a-ha         | 6 min ago | 1

I used below code:
WITH ranked_messages AS (
    SELECT
         messages.from_user_id, messages.to_user_id,
         messages.body, messages.sent_date,
         ROW_NUMBER() OVER
         (PARTITION BY messages.from_user_id
         ORDER BY messages.sent_date DESC) AS message_rank
    FROM
         messages
    WHERE
         messages.to_user_id = 31 OR
         messages.from_user_id = 31
)
SELECT *
FROM ranked_messages
WHERE message_rank = 1;

but I want also unread_message_count per user.
for an example:
select
     count(*) as unread_message_count
from
     messages
where
     to_user_id = 31 and
     is_read = false and
     from_user_id = 23

This should be calculated for each user who sends messages to the user, and vice versa
How can I achieve this result?

A: You can use window functions.  I think this is the logic:
WITH ranked_messages AS (
    SELECT m.from_user_id, m.to_user_id, m.body, m.sent_date,
           SUM(is_read::int) OVER (PARTITION BY from_user_id) as cnt
           ROW_NUMBER() OVER (PARTITION BY m.from_user_id ORDER BY m.sent_date DESC) AS message_rank
    FROM messages m
    WHERE 31 IN (m.to_user_id, m.from_user_id)
)
SELECT *
FROM ranked_messages
WHERE message_rank = 1;

A: You could include the count as a nested query:
WITH ranked_messages AS (
    SELECT messages.from_user_id, messages.to_user_id, messages.body, messages.sent_date,
        select count(*) as unread_message_count from messages where (to_user_id = 31 or from_user_id = 31) and is_read = false,
        ROW_NUMBER() OVER (PARTITION BY messages.from_user_id ORDER BY messages.sent_date DESC) AS message_rank
    FROM messages
    WHERE messages.to_user_id = 31 OR messages.from_user_id = 31
)
SELECT * FROM ranked_messages WHERE message_rank = 1;


text:
Q: Node.js express app and session management we are in the process of building a new app in node.js with express that connects to our parse server backend.  We have built native apps that already connect to our backend on iOS, Android and PHP.  All of them have the ability to log in the user and store the session data securely.
I'ts my understanding that node.js doesn't really store sessions like for example in PHP you can store them as a file on the server or to memcache or redis and test against parse->currentUser() to check if its valid.
How does one do this with node.js? We cant store any session data in a cookie since thats not secure.
Is using express-sessions and redis a good way to handle this?

A:
I'ts my understanding that node.js doesn't really store sessions like for example in PHP...

That's not a totally accurate understanding... it's more that Node.js doesn't really know or care how you handle your sessions.  That's where frameworks like Express, and their modules express-session, come into play.

Is using express-sessions and redis a good way to handle this?

If you're using Express, yes.  And, with that, you can use whatever session store you want, including Redis, Memcached, files, just like you're used to with PHP.

A: An approach that I've used in the past is to store your session ID in a cookie, but none of the session content.  That will allow you to reconnect with a prior session, as long as it's still valid.  You can also use LocalStorage if you want something a little more persistent than SessionStorage.  If you want something really persistent, you can manually save your session data to your database, and have the user request it if their browser data has been cleared.


text:
Q: Laravel Generate User data I'm new in Laravel and I want to generate fake data for the table Users.
Right know this is working fine:
UserFactory.php
$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

UsersTableSeeder.php
public function run() {
        factory(App\User::class, 5)->create();
}

DatabaseSeeder.php
public function run() {
        $this->call(UsersTableSeeder::class);
}

The previous code generates 5 rows in the User table and it is OK.
Now I would like to generate one more extra user (
in addition of the 5 rows already generated) with fixed fields like:
return [
        'name' => 'user test',
        'email' => 'user@mycompany.com',
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];

Where I have to put the above code? Do I have to generate a new UserFactory?

A: You can put the following code in your UsersTableSeeder.phps run() method right after your existing code:
factory(App\User::class)->create([
        'name' => 'user test',
        'email' => 'user@mycompany.com',
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ]);

You could also use 'password' => bcrypt(USERPASSWORDHERE), to create an encrypted string of USERPASSWORDHERE


text:
Q: Proguard files not being created I have several projects in Android Studio.  I am using
 buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
in my gradle script.  I have updated Android Studio to the latest version and use the latest version of build tools.  However, the proguard files, for example, mapping.txt, are never generated.  What am I doing wrong?  Thanks in advance!

A: I have solved this problem. The steps are:

*

*Create a new empty project in Android Studio, and the default file, proguard-rules.pro, is created in the app folder.

*Outside of Android Studio (e.g. Windows Explorer), copy proguard-rules.pro to the app directory.

*It will show up in your project when it is re-opened.

*Edit proguard-rules.pro as explained in the comments in the proguard-rules file.

*Generate your apk and you'll see that the mapping.txt and other proguard files are created.


text:
Q: Regex How to extract link from HTML with specific path I have been trying to extract link with specific URL using regex but failed I tried using the below regex to extract links using PHP.
preg_match_all('/\\/', $data1, $matches);

and the HTML is here just a snippet

Whole html contains a lot of links I need this link.

A: This will work if I don't misunderstood your question.
$html = '';
preg_match_all('/href="([^\s"]+)/', $html, $match);
print '
';
print_r($match);
print '
';
print $match[1][0];

Edited: As per comment, you didn't provided us the specific url that's why I just post a generic answer to capture href. See my below answer now. Used regex will be found here https://regex101.com/r/pnfz7E/1
$re = '/.*?<\/a>/m';
$str = 'SSD

How are you

HDD

Being Sunny

MSD

How are you

Being Sunny

GSD

How are you

LSD

Being Sunny
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
print '
';
print_r($matches);
print '
';


text:
Q: children of HTML element different background on line-break Why isn't all the children's background color the same as the parent's one HTML CSS if there is a line break separating the two,
for example if my font-size is 20:

Roberto#318:21

it works perfectly, but if my font size is 130

Roberto#318:21

and how to solve that simply?

A: The content width is greater than the element containing it, and it is floated, it will "overflow" outside of its container.
Then we can add overflow: auto; to the containing element to fix this problem :

  Roberto#318:21


text:
Q: Scheduled file transfer via WCF For the scheduled part I will use Quartz.net but for the file transferring part I am completely lost.
I found many examples but not close to what I need. I want to use two WCF libraries (no graphical interface) hosted in IIS to transfer files, no more than one GB. I understand the code (most of it) but when it comes to the ABC (address, bindings, contracts) it gets complicated. Can anyone point me to the right direction?

A: WCF is a powerful framework and flexible in terms of IPC. And that flexibility has accompanied of complexity as well ( may be for me when I was learning this stuff ).

*

*Address - Where is the service? It pertains to the location of your service just like URL.

Ex. http://localhost/YourServicePath/Service.svc

*Binding - How do I talk to the service? This is quiet complicated because it involve protocols and security. Binding defines on how both client and server will communicate to each other. There are different types of bindings. Bindings can be done through configuration file and/or programmatically.

Ex. BasicHttpBinding, WSHttpBinding ,WSDualHttpBinding ,
  NetTcpBinding, WSFederationHttpBinding, NetNamedPipeBinding,
  NetMsmqBinding,NetPeerTcpBinding

<bindings>
      <wsHttpBinding>
        <binding name="wshttpbind"  allowCookies="true" closeTimeout="00:01:00"
        receiveTimeout="00:01:00" />
      </wsHttpBinding>
  </bindings>

*Contracts - What can the service do for me? Contracts are all information exposed to both party that agrees to used for exchanging of message. It could be Data, Operation/Service/Methods or Message contract.

Ex. Service Contract, DataContract, Message Contract and Fault
  Contract.

[ServiceContract]
public interface ICalculate
{
   [OperationContract]
   double Add( double a, double b);
   [OperationContract]
   double Subtract( double a, double b);
}

I suggest to you to read article about it first for you not to lost along your development.


text:
Q: Android instrumentation test crashes on Firebase Test Lab but runs fine locally We have recently started adding Espresso instrumentation tests to our app, and I am trying to set up nightly runs of the tests on CircleCI. I got the Circle part working, and the test is getting triggered on Firebase Test Lab as expected, but the test runner is crashing every time with this exception:
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/swing/tree/DefaultTreeCellRenderer;
     FATAL EXCEPTION: Instr: androidx.test.runner.AndroidJUnitRunner
Process: [REDACTED], PID: 10933
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/swing/tree/DefaultTreeCellRenderer;
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:453)
    at androidx.test.internal.runner.TestLoader.doCreateRunner(TestLoader.java:72)
    at androidx.test.internal.runner.TestLoader.getRunnersFor(TestLoader.java:104)
    at androidx.test.internal.runner.TestRequestBuilder.build(TestRequestBuilder.java:793)
    at androidx.test.runner.AndroidJUnitRunner.buildRequest(AndroidJUnitRunner.java:547)
    at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:390)
    at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2075)
Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.swing.tree.DefaultTreeCellRenderer" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/android.test.mock.jar", zip file "/data/app/[REDACTED]/base.apk", zip file "/data/app/[REDACTED]/base.apk"],nativeLibraryDirectories=[/data/app/[REDACTED]/lib/arm64, /data/app/[REDACTED]/lib/arm64, /data/app/[REDACTED]/base.apk!/lib/arm64-v8a, /data/app/[REDACTED]/base.apk!/lib/arm64-v8a, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    ... 8 more

We did include these in our build.gradle:
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'

What could be causing that exception?
I'm getting the same issue when manually using the Firebase Test Lab web GUI in https://console.firebase.google.com/
The tests are running fine locally, both in Android Studio and with adb shell am instrument -w -r -e debug false -e package '[REDACTED]' [REDACTED].debug.test/androidx.test.runner.AndroidJUnitRunner.

A: For our particular case, it was solved by using --environment-variables in the gcloud firebase test android run command, to set the test package (ours is our app package followed by .test) and debug=false. So something like this:
gcloud firebase test android run \
--type instrumentation \
--app [REDACTED].apk \
--test [REDACTED]-androidTest.apk \
--environment-variables package=[REDACTED],debug=false \
--num-flaky-test-attempts 3 \
--device model=blueline,version=28,locale=en_US,orientation=portrait \
--timeout 20m


text:
Q: jquery insert data into next row I am displaying data in table as below
{'headers': [u'first',
             u'last',
             u'age'],
 'values': [[u'sam',u'tom', 31]]}

using jquery as
jQuery.each(data, function(index, value) {
    var tr = $('
');
    for (var i = 0; i<value.length; i++){
        if (index=="headers"){
            tr.append("" + value[i] + "	");
        }
        else{
            for (var j = 0; j<value[i].length; j++){
                tr.append("" + value[i][j] + "	");
            }
        }
    }

    $("#table1").append(tr);
});

And it displays properly with header row and first row. But when I have data with 2 values list as
 'values': [[u'sam', u'tom', 31],
            [u'dean', u'tom', 28]]

rather that creating second row it displays whole 6 values in one row.
How can get second list to display in next row?

A: You are closing your rows before adding anything to them with

Try this:
jQuery.each(data, function(index, value) {
    var tr = $('
');
    for (var i = 0; i<value.length; i++){
        if (index=="headers"){
            tr.append("" + value[i] + "	");
        }
        else{
            for (var j = 0; j<value[i].length; j++){
                tr.append("" + value[i][j] + "	");
            }
            tr.append("

");
        }
    }
    tr.append("
");
    $("#table1").append(tr);
});

A: You want to add a new row for each array in values:

var data = {
  'headers': ['first','last','age'],
  'values': [
    ['sam','tom', 31],
    ['johnny','walker', 69]
  ]
}
$.each(data, function(index, value) {
  if (index == "headers") {
    let tr = $('
');
    $.each(value, function(k, v){
      tr.append("" + v + "	");
    })
    $("#table1").append(tr);
  } else {
    $.each(value, function(i,row) {
      let tr = $('
');
      $.each(row, function(k, v){
        tr.append("" + v + "	");
      })
      $("#table1").append(tr);
    });
  }
});


text: Q: How to prove that the Riemann surface $\{(x,y)\in\mathbb{C}^2: y^2=x(x^2-1)(x^2-4)\}$ admits a non-constant holomorphic function? I have some idea about using the removable singularity theorem but have difficulty in carrying out the whole proof. Also, I'm interested in why this riemann surface cannot admit a bounded non-const holomorphic function.


text:
Q: Error handling in PowerShell provoked by a null dsquery I want to avoid errors provoked by a null dsquery. I tried this:
try {
     dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >> output.txt
}
catch [Exception] {
    return $_.Exception.Message
}

But I'm still getting:
dsget : dsget failed:'Target object for this command' is missing.
At ExpiringCertificates.ps1:35 char:49
+         dsquery user forestroot -samid $a[$i] | dsget user -email | Select-Strin ...
+                                                 ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (dsget failed:'T...nd' is missing.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

type dsget /? for help.

How should I handle it?

A: Try this:
try
{
    dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >> output.txt
}
catch
{
    Write-Error -ErrorRecord $_
}

If $ErrorActionPreference is set to 'Stop', Write-Error will throw an exception and halt execution. Otherwise, it will print to the error stream and continue execution. This allows the caller to decide whether or not to continue on error and keeps you from having to set global variables in your scripts.
If you need to print and return the error message, use the -ErrorVariable parameter:
catch
{
    $errorVar = $null
    Write-Error -ErrorRecord $_ -ErrorVariable errorVar
    return $errorVar
}

Or, if you need to return the error message without printing it, add the "2>" redirect:
catch
{
    $errorVar = $null
    Write-Error -ErrorRecord $_ -ErrorVariable errorVar 2> $null
    return $errorVar
}

A: dsquery and dsget are not PowerShell commands, so PowerShell looks at the standard error, and processes it, turning it into an ErrorRecord with a "NativeCommandError" exception attached to it, and then sends a text representation of that record to the standard output.
However, if you process the standard error yourself, you have a bit more flexibility:
dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line 2>&1
If ($_ -is [Management.Automation.ErrorRecord]) {
    $message = $_.Exception.Message
    # Do what you want with $message.
} Else {
    $_ >> output.txt
}

A: This might work for you:
try {
     $erroractionpreference = 'stop'
     dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >output
}
catch [Exception] {
    return $_.Exception.Message
}


text:
Q: C# and PowerPoint 2010 integration I'm making "something" (I don't know how to define it yet), and what does is create a pptx presentation and some slides... but I'm facing some problems: I can't change the background color/image of my slides and textboxes... and I can't figure it out... Can anyone help me?

A: The thing you are probably missing with regards to setting colors of objects on your slides is that COM Interop thinks about colors slightly differently than what you may be used to in the .NET Framework.
In the .NET Framework, we represent colors using the aptly-named Color structure, which encapsulates values for the alpha channel of the color, and its red, green, and blue components. However, COM Interop represents colors as an Integer value, in the format BGR. That means that the component values for red, green, and blue are actually stored as blue, green, and red.
However, the .NET Framework provides an easy, built-in way to convert between these two color formats: the ColorTranslator.ToOle and ColorTranslator.FromOle methods. So, you should be able to change the background color of your PowerPoint slide using the following code:
//Create a color
Color myBackgroundColor = Color.LimeGreen;

//Translate to an OLE color
int oleColor = ColorTranslator.ToOle(myBackgroundColor);

//Set the background color of the slide
mySlide.Background.Fill.ForeColor.RGB = oleColor;

Conversely, to retrieve the current background color as a .NET color, you'll have to do the opposite:
//Get the current background color of the slide
int oleColor = mySlide.Background.Fill.ForeColor.RGB;

//Translate to a .NET Color
color myBackgroundColor = ColorTranslator.FromOle(oleColor);

And, of course, if you want to set the foreground (fill) color of a shape, you can simply set its ForeColor property, like so:
//Create a color
Color myForegroundColor = Color.Aqua;

//Translate to an OLE color
int oleColor = ColorTranslator.ToOle(myForegroundColor );

//Set the foreground color of a shape
myShape.Fill.ForeColor.RGB = oleColor;

A: I was having the same issue until I discovered that you need to set slide.FollowMasterBackground to false:
Slide slide = presentation.Slides.AddSlide(presentation.Slides.Count + 1, layout);
slide.FollowMasterBackground = Microsoft.Office.Core.MsoTriState.msoFalse;
slide.Background.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);

A: I figured it out... in order to change the background of a slide u must first call the method Fill.Background() before changing the color/picture!!! tks everyone for the help


text:
Q: In Redux, replace dispatch in action creator Given my action creator:
export const REQUEST_ARTICLES = 'REQUEST_ARTICLES'
export const RECEIVE_ARTICLES = 'RECEIVE_ARTICLES'
export const CHANGE_PAGE = 'CHANGE_PAGE'

export const changePage = (currentPage) => ({
    type: CHANGE_PAGE,
    currentPage,
})

export const requestArticles = () => ({
    type: REQUEST_ARTICLES,
})

export const receiveArticles = json => ({
    type: RECEIVE_ARTICLES,
    posts: json.hits,
})

export const fetchArticles = () => async (dispatch) => {
    try {
        await dispatch(requestArticles())
        let response = await fetch('www.abc.com')
        let json = await response.json()
        await dispatch(receiveArticles(json))
    } catch (e) {
        console.log('error:', e)
    }
}

So I am using dispatch inside action creator. But if I have to dispatch multiple actions, then my code would be
        try {
            await dispatch(requestArticles1())
            await dispatch(requestArticles2())
            await dispatch(requestArticles3())
            await dispatch(requestArticles4())
            await dispatch(requestArticles5())
            let response = await fetch('www.abc.com')
            let json = await response.json()
            await dispatch(receiveArticles(json))
        } catch (e) {
            console.log('error:', e)
        }

I already use mapDispatchToProps in the component. Is there any similar way/method I can use in action creator so that I don't have to dispatch actions manually one by one?

A: redux's store.dispatch() is not an asynchronous function, so there is no need to await its return.  It will still work because awaiting non-async functions casts them to an immediately-resolving promise.
With regard to dispatching multiple actions, you will need to manually dispatch every action that you need.  The question becomes: why do you need to dispatch so many actions?  In general for an ajax-calling thunk you will use a started, succeeded and failed action, and not many more.
export const fetchArticles = () => async (dispatch) => {
    try {
        dispatch(requestArticlesStarted())
        const response = await fetch('www.abc.com')
        const json = await response.json()
        dispatch(requestArticlesSucceeded(json))
    } catch (e) {
        console.log('error:', e);
        dispatch(requestArticlesFailed(e));
    }
}


text:
Q: Nginx Cache file is too small I have tried enabling Nginx caching in my Elastic Beanstalk application. For this matter I've added the following lines in my Nginx configuration file -
proxy_cache_path /tmp levels=1:2 keys_zone=analytics-cache:50m max_size=1g inactive=5m use_temp_path=off;
proxy_cache           analytics-cache;

The problem is that once I start up Nginx I get the following error in the error.log - cache file "/tmp/restore_docker_image_names.sh" is too small.
I have no idea what this error means, and it persisted even after trying to increase the size of my cache key from 5m to 50m.
How can I avoid this error?

A: The fact that nginx is trying to open a .sh file for it's cache looks suspicious. /tmp is used by the whole system so non cache files already exist there.
Use a proxy_cache_path that is empty and only nginx will use, like /tmp/nginx/cache or /var/cache/nginx


text:
Q: Google Streetview Javascript API: most panorama functions return undefined I'm trying to extend the Google street view API example, but some of the functions listed in the API simply don't seem to work. Here is my example code:
function initialize() {
        var fenway = {lat: 42.345573, lng: -71.098326};
        var mypov = {heading: -90, pitch: 20};
        var panorama = new google.maps.StreetViewPanorama(
            document.getElementById('pano'), {
              position: fenway,
              pov: mypov
            });
        var curr_pov = panorama.getPov();
        var curr_loc = panorama.getLocation();
        var links = panorama.getLinks();
        var photo_pov = panorama.getPhotographerPov()
      }

At the end of this function, curr_pov contains an object with heading and pitch, but the remaining variables are undefined.
The API at https://developers.google.com/maps/documentation/javascript/reference?csw=1#StreetViewPanorama suggests that getPov, getLinks and getPhotographerPov should all be methods in the StreetViewPanorama class. Any idea what am I doing wrong? Thanks in advance for any help.


text:
Q: Confusion between distinct and group by I am confused on DISTINCT & GROUP BY in following scenario.
I have a table with columns a - z. I need to make a query with following conditions.
select DISTINCT a, b, c, d from table_name

But I need all the columns a - z from above query where I can DISTINCT a, b, c, d
So should I execute following query
select * from table_name GROUP BY a, b, c, d

I am confused between DISTINCT & GROUP BY in this case.
Can anybody please clear me
Thanks.

A: Use window functions:
select t.*
from (select t.*,
             row_number() over (partition by a, b, c, d order by a) as seqnum
      from t
     ) t
where seqnum = 1;

Aggregation is not appropriate for this problem.  This query:
select *
from table_name
group by a, b, c, d;

is syntactically incorrect -- and happily, MySQL no longer (by default settings) allows this syntax.  The problem is that you end up with unaggregated columns (such as e, f, and so on) in the select.  That is not allowed in SQL.  You need to be explicit with aggregation queries.


text:
Q: Add item to many to many entity in Entity Framework So I have these 2 entities
public class Player
{
        [Key]
        public Guid Id { get; private set; }
        public Guid ActiveGroupId { get; set; }
        public virtual Group ActiveGroup { get; set; }
        public virtual ICollection<Group> Groups { get; set; }
}

public class Group
{
        [Key]
        public Guid Id { get; private set; }
        public string Name { get; set; }
        public virtual ICollection<Player> Players { get; set; }
}

So what I wanna do right now is in Configuration.Seed if the players have ActiveGroup and don't have group yet. Then add the active group to the Player.Groups. Right now I always failed with error Multiplicity constraint violated. The role 'Player_Groups_Source' of the relationship 'Entities.Player_Groups' has multiplicity 1 or 0..1.
This is what I did
foreach (var player in context.Players.ToList())
{
    var activeGroup = context.Groups.First(x => x.Id == player.ActiveGroupId);
    player.Groups.Add(activeGroup);
}
context.SaveChanges();

I am using EF 6.4.4 and running it on mac (if that is matter). Any idea what is wrong with this approach?

A: you need to make sure that your ManyToMany relation is correct defined
public class PlayerMap : EntityTypeConfiguration<Player>
    {
        public PlayerMap()
        {
            HasMany(a => a.Groups)
                .WithMany(a => a.Players);
        }
    }

Then you need to initialize the collection of Groups:
public class Player
{
    [Key]
    public Guid Id { get; private set; }
    public Guid ActiveGroupId { get; set; }
    public virtual Group ActiveGroup { get; set; }
    public virtual ICollection<Group> Groups { get; set; } = new List<Group>();
}

then you can add a group to a player.


text:
Q: moveRowAtIndexPath – animation of dropping the cell? As I enter the canMoveRowAtIndexPath mode, everything is beautifully animated (other cells sliding as I drag the cell above them) until I drop the cell to a desired location. It just pops in in no time. How can I animate it (as it's for example in Reminders app)?
PROBLEM SOLVED by maddy's comment.

A: Check this Link might be help full for you.
UITableViewExtendedAnimations category allows to perform new animations,
such as moving cells, exchanging cells, and making transitions from one
cell to another.
There are three new methods on UITableView:
-moveRowAtIndexPath:toIndexPath:
-transitRowAtIndexPath:toRowIndexPath:
-exchangeRowAtIndexPath:withRowAtIndexPath:

This was done using a regular Objective-C category.
To perform such animations UITableViewDelegate protocol was extended.
There are a couple of new methods you have to implement to make these
animations possible. Take a look at example project to see that methods.
Video of the sample project:
http://www.youtube.com/embed/bC-YTq9C0Sk


text:
Q: How can I call MSSQL encrypted Stored Procedures from Java? There is MSSQL database with encypted Stored Procedures and my application doesn't see them (I use different jdbc drivers).
I have two question.
How can I get list of these encrypted Stored Procedures?
How can I invoke MSSQL encrypted Stored Procedures from Java?

A: How can I get list of these encrypted Stored Procedures?
SELECT SCHEMA_NAME(p.schema_id) + '.' + p.name
FROM sys.procedures p
WHERE OBJECTPROPERTY(p.object_id, 'IsEncrypted')  = 1

How can I invoke MSSQL encrypted Stored Procedures from Java?
Should be no difference between encrypted and non-encrypted stored procedures when you invoke their from Java.


text:
Q: Symfony 3 NoSuchPropertyException Hi everybody  i'm working on a symfony 3.3 project and i have an error i came not to resolve it even i searched in similar posts here but i don't find any solution that works for me.
I have two entites "Cours" and "Categorie" (in french) these two entities have manytomany association. The problem is when i go to the page that creates new Cours i get this error

Neither the property "categories" nor one of the methods
  "getCategories()", "categories()", "isCategories()",
  "hasCategories()", "__get()" exist and have public access in class
  "LearnBundle\Entity\Categorie".

this is Cours.php code
    <?php
namespace LearnBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Cours
 *
 * @ORM\Table(name="cours")
 * @ORM\Entity(repositoryClass="LearnBundle\Repository\CoursRepository")
 */
class Cours
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=255, unique=true)
     * @Assert\NotBlank()
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $image;

    /**
     * @var string
     *
     * @ORM\Column(name="video_intro", type="string", length=255, unique=true)
     * @Assert\NotBlank()
     */
    private $videoIntro;

    /**
     * @var string
     *
     * @ORM\Column(name="serie_videos", type="string", length=255, unique=true)
     * @Assert\NotBlank()
     */
    private $serieVideos;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     * @Assert\NotBlank()
     */
    private $description;

    /**
     * @var string
     *
     * @ORM\Column(name="prerequis", type="text")
     * @Assert\NotBlank()
     */
    private $prerequis;

    /**
     * @var string
     *
     * @ORM\Column(name="message", type="text")
     * @Assert\NotBlank()
     */
    private $message;

    /**
     * @var string
     *
     * @ORM\Column(name="etat", type="string", length=255)
     */
    private $etat;

    /**
     * @ORM\ManyToMany(targetEntity="LearnBundle\Entity\Categorie", inversedBy="cours")
     * @ORM\JoinTable(name="cours_categories")
     */
    private $categories;

    /**
     * @ORM\OneToMany(targetEntity="Fichier", mappedBy="cours")
     * @Assert\Type(type="AppBundle\Entity\Fichier")
     * @Assert\Valid()
     */
    private $fichier;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="cours")
     * @ORM\JoinTable(name="cours_etudiants")
     */
    private $etudiants;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="cours")
     * @ORM\JoinColumn(name="formateur", referencedColumnName="id")
     */
    private $formateur;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titre
     *
     * @param string $titre
     *
     * @return Cours
     */
    public function setTitre($titre)
    {
        $this->titre = $titre;

        return $this;
    }

    /**
     * Get titre
     *
     * @return string
     */
    public function getTitre()
    {
        return $this->titre;
    }

    /**
     * Set image
     *
     * @param string $image
     *
     * @return Cours
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set videoIntro
     *
     * @param string $videoIntro
     *
     * @return Cours
     */
    public function setVideoIntro($videoIntro)
    {
        $this->videoIntro = $videoIntro;

        return $this;
    }

    /**
     * Get videoIntro
     *
     * @return string
     */
    public function getVideoIntro()
    {
        return $this->videoIntro;
    }

    /**
     * Set serieVideos
     *
     * @param string $serieVideos
     *
     * @return Cours
     */
    public function setSerieVideos($serieVideos)
    {
        $this->serieVideos = $serieVideos;

        return $this;
    }

    /**
     * Get serieVideos
     *
     * @return string
     */
    public function getSerieVideos()
    {
        return $this->serieVideos;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Cours
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set prerequis
     *
     * @param string $prerequis
     *
     * @return Cours
     */
    public function setPrerequis($prerequis)
    {
        $this->prerequis = $prerequis;

        return $this;
    }

    /**
     * Get prerequis
     *
     * @return string
     */
    public function getPrerequis()
    {
        return $this->prerequis;
    }

    /**
     * Set message
     *
     * @param string $message
     *
     * @return Cours
     */
    public function setMessage($message)
    {
        $this->message = $message;

        return $this;
    }

    /**
     * Get message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->categories = new ArrayCollection();
        $this->fichier= new ArrayCollection();
    }

    /**
     * Add category
     *
     * @param \LearnBundle\Entity\Categorie $category
     *
     * @return Cours
     */
    public function addCategory(\LearnBundle\Entity\Categorie $category)
    {
        $this->categories[] = $category;

        return $this;
    }

    /**
     * Remove category
     *
     * @param \LearnBundle\Entity\Categorie $category
     */
    public function removeCategory(\LearnBundle\Entity\Categorie $category)
    {
        $this->categories->removeElement($category);
    }

    /**
     * Get categories
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCategories()
    {
        return $this->categories;
    }

    /**
     * Add etudiant
     *
     * @param \LearnBundle\Entity\User $etudiant
     *
     * @return Cours
     */
    public function addEtudiant(\LearnBundle\Entity\User $etudiant)
    {
        $this->etudiants[] = $etudiant;

        return $this;
    }

    /**
     * Remove etudiant
     *
     * @param \LearnBundle\Entity\User $etudiant
     */
    public function removeEtudiant(\LearnBundle\Entity\User $etudiant)
    {
        $this->etudiants->removeElement($etudiant);
    }

    /**
     * Get etudiants
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getEtudiants()
    {
        return $this->etudiants;
    }

    /**
     * Set etat
     *
     * @param string $etat
     *
     * @return Cours
     */
    public function setEtat($etat)
    {
        $this->etat = $etat;

        return $this;
    }

    /**
     * Get etat
     *
     * @return string
     */
    public function getEtat()
    {
        return $this->etat;
    }

    /**
     * Set formateur
     *
     * @param \LearnBundle\Entity\User $formateur
     *
     * @return Cours
     */
    public function setFormateur(\LearnBundle\Entity\User $formateur = null)
    {
        $this->formateur = $formateur;

        return $this;
    }

    /**
     * Get formateur
     *
     * @return \LearnBundle\Entity\User
     */
    public function getFormateur()
    {
        return $this->formateur;
    }

    /**
     * Add fichier
     *
     * @param \LearnBundle\Entity\Fichier $fichier
     *
     * @return Cours
     */
    public function addFichier(\LearnBundle\Entity\Fichier $fichier)
    {
        $this->fichier[] = $fichier;

        return $this;
    }

    /**
     * Remove fichier
     *
     * @param \LearnBundle\Entity\Fichier $fichier
     */
    public function removeFichier(\LearnBundle\Entity\Fichier $fichier)
    {
        $this->fichier->removeElement($fichier);
    }

    /**
     * Get fichier
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getFichier()
    {
        return $this->fichier;
    }

}

this is CoursType.php code
    <?php

namespace LearnBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use LearnBundle\Entity\Cours;

class CoursType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('titre')
        ->add('image', FileType::class, array('data_class' => null))
        ->add('videoIntro')
        ->add('serieVideos')
        ->add('description')
        ->add('prerequis')
        ->add('message')
        ->add('categories',EntityType::class, array(
                'multiple' => 'true',
                'class' => 'LearnBundle:Categorie',
                'choice_label' => 'categories'

                )

            )
        ->add('Fichier', CollectionType::class, array(
            'entry_type' => FichierType::class,
            'entry_options' => array('label' => false),
        ))

        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'LearnBundle\Entity\Cours'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'learnbundle_cours';
    }

}

this is Categorie.php code
    <?php

namespace LearnBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Categorie
 *
 * @ORM\Table(name="categorie")
 * @ORM\Entity(repositoryClass="LearnBundle\Repository\CategorieRepository")
 */
class Categorie
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255, unique=true)
     */
    private $nom;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image;

    /**
     * @ORM\ManyToMany(targetEntity="\LearnBundle\Entity\Cours", mappedBy="categories")
     */
    private $cours;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nom
     *
     * @param string $nom
     *
     * @return Categorie
     */
    public function setNom($nom)
    {
        $this->nom = $nom;

        return $this;
    }

    /**
     * Get nom
     *
     * @return string
     */
    public function getNom()
    {
        return $this->nom;
    }

    /**
     * Set image
     *
     * @param string $image
     *
     * @return Categorie
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->cours = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add cours
     *
     * @param \LearnBundle\Entity\Cours $cour
     *
     * @return Categorie
     */
    public function addCours(\LearnBundle\Entity\Cours $cour)
    {
        $this->cours[] = $cour;

        return $this;
    }

    /**
     * Remove cours
     *
     * @param \LearnBundle\Entity\Cours $cour
     */
    public function removeCours(\LearnBundle\Entity\Cours $cour)
    {
        $this->cours->removeElement($cour);
    }

    /**
     * Get cours
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCours()
    {
        return $this->cours;
    }
}

this is code of newAction function in CoursController.php
public function newAction(Request $request)
    {
        $cour = new Cours();
        $cour->setEtat('en_attente');
        $form = $this->createForm('LearnBundle\Form\CoursType', $cour);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            //traitement d'image de cours
            $image = $cour->getImage();
            $imageName = md5(uniqid()).'.'.$image->guessExtension();
            $image->move($this->getParameter('images_directory'),$imageName);
            $cour->setImage($imageName);
            //enregistrement de cours

            $em->persist($cour);
            $em->flush();

            return $this->redirectToRoute('cours_show', array('id' => $cour->getId()));
        }

    return $this->render('cours/new.html.twig', array(
        'cour' => $cour,
        'form' => $form->createView(),
    ));
}

A: Change choice_label' => 'categories' by
choice_label' => 'nom'


text:
Q: No swap in Xubuntu 14.04 LTE with full disk/system encryption I'm a newbee to Linux. I installed Xubuntu 14.04 LTE on my 1.6GHz/2GB RAM/120 GB SSD HDD netbook. Everything goes smoothly, except I realized that during booting and logging in there was a warning that swap file was unavailable. I used the hints from this forum and from others to remove this, but the system still lacks swap.
Please note that I had no such issues with a similar notebook installation, during which I did not use encrypted partition etc.
So, in the netbook with issues, GParted reports the following partitions:
/dev/sda1 [keys icon] ext2  /boot  243MiB
/dev/sda2  extended     111.55 GiB
   /dev/sda5 [exclamation mark icon]  crypt-liks   111.55 GiB
So, no swap is available. Is it really an issue, or shall I used a certain file as a swap since the disk and partitions are encrypted?
I'd appreciate the suggestions from expert users.

A: I have similar problem on similar system :), but with only Home directory encrypted...
I just copy^paste answers from another forum:

*

*Cannot reduce lv partion to allow for swap partition.

*At first: on most systems today with 4GB RAM and more there is no need for a swap partition. Except, of cause, you are doign very RAM intensive things.

*Also there is the option to create a swap file instead of a partition.
Details: https://help.ubuntu.com/community/SwapFaq


text:
Q: Jquery MoreThan or LessThan I'm trying to create a responsive website with a fixed navigation only when the document width is above 769px.
I've got the following code which works fine when i test it using alerts to say whether the window is bigger than the size or lower than the size when re sizing.
However when i add my sticky header script into the else statement it doesn't work and i cant figure out why.
Can anyone point me in the right direction.
Thanks
This is the window size statement:
 $(window).resize(function() {
 if ($(window).width() < 769) {
 alert('Less than 769');
 }
 else {
 alert('More than 769');
 }
 });

And this is the code I'm trying to use if the window width is bigger than 769:
var aboveHeight = $('header').outerHeight();

$(window).scroll(function() {

    if ($(window).scrollTop() > aboveHeight) {

        $('nav').addClass('fixed').css('top', '0').next().css('padding-top', '99px');
    } else {

        $('nav').removeClass('fixed').next().css('padding-top', '0');
    }
});

Thanks

A: Just save the state ant test in your scroll event
var isRightSize = false;

 $(window).resize(function() {
     if ($(window).width() < 769) {
         isRightSize = false;
     }
     else {
         isRightSize = true;
     }
 });

var aboveHeight = $('header').outerHeight();

$(window).scroll(function() {

    if(!isRightSize)
        return false;

    if ($(window).scrollTop() > aboveHeight) {

        $('nav').addClass('fixed').css('top', '0').next().css('padding-top', '99px');
    } else {

        $('nav').removeClass('fixed').next().css('padding-top', '0');
    }
});


text:
Q: Sorting table rows by date comparing DateTime in seeds file and Date.now() I am trying to render a table with a list of appointment times that have a DateTime in my seeds file. I'm trying to sort them by date, and also conditionally render based on whether that time is in the past or future. I'm struggling to format it properly to be able to sort.
I've converted the array of objects from state so that every date attribute is in the Javascript date format.
Here is the relevant section:
import React, { Component } from "react";

export default class LessonsList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current_time: Date.now(),
      lessons: []
    };
  }

  componentDidMount() {
    const token = localStorage.getItem("current_user");
    fetch("http://localhost:3000/api/v1/lessons/", {
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
      .then(resp => resp.json())
      .then(lessons => {
        lessons.map(lesson => {
          lesson.timeslot.realdate = new Date(lesson.timeslot.realdate);
          return lesson;
        });
        this.setState({
          lessons
        });
      });
  }

  sortDates = () => {
    let sortedDates = this.state.lessons.sort(function(date, lesson) {
      return Date.now(date) - lesson.timeslot.realdate;
    });
    return sortedDates;
  };

  renderTableData = () => {
    // map over sorted array from separate function
    return this.state.lessons.length ? (
      this.sortDates().map(lesson => {
        console.log(lesson.timeslot.realdate > Date.now());
        return (

            {lesson.id}
            {lesson.teacher.name}

              {lesson.timeslot.month_name} {lesson.timeslot.date}

            {lesson.timeslot.hour}:00

        );
      })
    ) : (

'Loading'

    );
  };

  render() {
    console.log(this.state.lessons);
    return (

Lessons

              Lesson ID
              Teacher
              Date
              Time

{this.renderTableData()}

    );
  }
}

I think I need to sort by date and then map over what is returned to render the table rows. It's not seeming to have any effect. Thanks!

A: Your sort function needs to return -1, 0, or 1 to work properly. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


text:
Q: ModuleNotFoundError: No module named 'odata' Python I have installed the following pip on the anaconda power shell using: pip install -U pyodata. The pip installed successfully, however when I try to import the script in Python from pyodata import ODataService I get the following error: ModuleNotFoundError: No module named 'odata'
Would like to know if someone experienced the same problem?

A: I dont really kown about pyodata but there seems to be a ODataService module in odata.
https://github.com/tuomur/python-odata/blob/master/README.md
However this module is outdated, the current module can be found here: https://github.com/SAP/python-pyodata

A: This looks like user copy-paste error during coding, mismatching two different packages.
Pyodata so far never had OdataService. Correct initialization is documented here: https://pyodata.readthedocs.io/en/latest/usage/initialization.html


text:
Q: Running Gunicorn Flask app in Docker [CRITICAL] WORKER TIMEOUT when starting up I want to run a Flask web services app with gunicorn in Docker. Upon startup, the app loads a large machine learning model.
However, when I run gunicorn within Docker I received the following timeouts and it just keeps spawning workers.
[2019-12-12 21:52:42 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1198)
[2019-12-12 21:52:42 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1204)
[2019-12-12 21:52:42 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1210)
[2019-12-12 21:52:42 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1211)
[2019-12-12 21:52:42 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1222)
[2019-12-12 21:52:42 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1223)
[2019-12-12 21:52:42 +0000] [1264] [INFO] Booting worker with pid: 1264
[2019-12-12 21:52:42 +0000] [1265] [INFO] Booting worker with pid: 1265
[2019-12-12 21:52:42 +0000] [1276] [INFO] Booting worker with pid: 1276
[2019-12-12 21:52:42 +0000] [1277] [INFO] Booting worker with pid: 1277
[2019-12-12 21:52:42 +0000] [1278] [INFO] Booting worker with pid: 1278
[2019-12-12 21:52:42 +0000] [1289] [INFO] Booting worker with pid: 1289

Running it as a flask app within Docker or running the flask app with (or without) gunicorn from the command line works fine. It also works with gunicorn if I remove the machine learning model.
For example:
$python app.py

$gunicorn -b 0.0.0.0:8080 --workers=2 --threads=4 app:app

$gunicorn app:app

Here is my Dockerfile with the Flask development server. Works fine.
ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD python app.py

If I run gunicorn as follows it just keeps spawning workers:
CMD gunicorn -b 0.0.0.0:8080 --workers=2 --threads=4 app:app
or
CMD ["gunicorn", "app:app"]

gunicorn has a --timeout=30 parameter. Defaults to 30 seconds which I increased to 300. This did not appear to have an affect.
Note: I rewrote the app for the Starlette library and received the same results!
Any guidance is appreciated.
Thanks,
Jay

A: I needed to add the gunicorn --timeout as follows:
CMD gunicorn --timeout 1000 --workers 1 --threads 4 --log-level debug --bind 0.0.0.0:8000 app:app

I also ran into problems deploy on Google Cloud Platform. The log only showed a kill message. Increasing the memory in the compute instance solved that problem.

A: try this
CMD["gunicorn", "--timeout", "1000", "--workers=1","-b", "0.0.0.0:8000","--log-level", "debug", "manage"]


text:
Q: HTML select element - Selected item use option font I am creating a font dropdown list on a web page. I have styled each option element with the font that it represents:-
<option value="Arial, Helvetica, sans-serif" style="font-family: Arial,Helvetica,sans-serif;">Arial</option>

When I expand the dropdown it looks correct but when I select an item, the dropdown does not use the font of the selected option. Is there a way I can make it update the font when selecting options?
jsFiddle - http://jsfiddle.net/bq2d9/

A: Try this:
http://jsfiddle.net/Rp9gp/1/
Try this to change the style in the dropdown:
http://jsfiddle.net/Rp9gp/2/

A: Try add:
onChange="this.style.fontFamily=this.value;"

http://jsfiddle.net/bq2d9/5/
Do note that the font in the drop-down displays properly in Firefox, but not in Chrome. However, after selection, both will display the text in the correct font.
Chrome does not support different fonts in each selection option.

To get a cross-browser font selector that displays the font of each option, you will have to get a plugin.
Looking at jQuery plugins, there are a large number. It is unclear exactly which of them support individual styling. I can find a few where options can be individually styled, however, they also can look ugly. For the ones which look better, it is sometimes hard to know whether they can be individually styled.
The best I can find is jQuery-Font-Chooser - https://github.com/CD1212/jQuery-Font-Chooser. It looks good enough, and response time is ok.
Otherwise, for other plugins, you can search, for example, "jquery select box" or "jquery font selector".

A: In this case, you need some customization that every browser might not support and you will face problems like the one you mentioned. So I certainly recommend you to use a fully customized combobox. A jquery one might be good for you.
Here is the link to ComboBox plugin: http://archive.plugins.jquery.com/plugin-tags/combobox


text:
Q: How to zip but not in pair? Let a
Seq( Seq(1, 2, 5) , Seq(3, 4, 5) , Seq(2, 1, 0) )

I'd want to get :
Seq( Seq(1, 3, 2) , Seq(2, 4, 1) , Seq(5, 5, 0) )

For the moment I wrote this :
points.reduce((point_1, point_2) => point_1.zip(point_2))

With : points the Seq[Seq[Double]] and point_1 and point_2 the Seq[Double].
It returns an error because Scala's interpreter seems to try to make a pair with a Seq[(Double, Double)] and Double (I think). In my example, it tries to make a pair with Seq( (1, 3) ) and 2. I can be wrong but it's my interpretation of the problem for now.
Well, how to solve this bug ? I feel like I need to use flatten, no ?

A: The standard library can do that for you.
Seq( Seq(1, 2, 5) , Seq(3, 4, 5) , Seq(2, 1, 0) ).transpose
//res0: Seq[Seq[Int]] = List(List(1, 3, 2), List(2, 4, 1), List(5, 5, 0))

update
If you're intent on doing it yourself, in a functional fashion, here's one way.
val ssi: Seq[Seq[Int]] = Seq(Seq(1, 2, 5), Seq(3, 4, 5), Seq(2, 1, 0))

ssi.zipWithIndex.map{case (s,x) =>
  s.indices.map(ssi(_)(x))
}

A: If you want to do it using map and fold,
val seqInput = Seq( Seq(1, 2, 5) , Seq(3, 4, 5) , Seq(2, 1, 0) )
// seqInput: Seq[Seq[Int]] = List(List(1, 2, 5), List(3, 4, 5), List(2, 1, 0))

val seqOutput = seqInput
  .map(s => Seq(s))
  .fold(
    seqInput.head.map(_ => Seq.empty[Int])
  )({
    case (acc, seq) => acc.zipWithIndex.map({ case (accSeq, i) => accSeq :+ seq.head(i) })
  })
// seqOutput: Seq[Seq[Int]] = List(List(1, 3, 2), List(2, 4, 1), List(5, 5, 0))


text:
Q: twisted defer make the assignment of class instance variables is invalid I have a class A with two methods, method_one which uses a defer and method_two , in callback function I set a value to self.value and add it to defer's callback chain. but after that the self.value is still the original value in method_two. in short, the assignment of self.value in callback function is invalid.
from twisted.internet import utils, reactor
class A(object):

    def __init__(self):
        self.value = []

    def method_one(self):
        d = utils.getProcessOutput('/bin/sh', ('-c', 'ls /home')) # return a defer
        def set_self_value(result):
            self.value = result.split()  # assign result.split() to self.value
        d.addCallback(set_self_value)

    def method_two(self):
        print self.value  # it is still [] rather than result

a = A()
a.method_one()
a.method_two()
reactor.run()

output:
[]  # i expect self.value is ['lost+found', 'user']
lost+found
user

thanks in advance :-)

A: The issue is that as the method_one is deferred, so,  instead of calling set_self_value right away it first moves on to the next step a.method_two(), hence as at that time the value is not yet set you get an empty list.
To make sure method_two is called after method_one add it to the callback chain:
import twisted
from twisted.internet import utils
from twisted.internet import reactor

class A(object):

    def __init__(self):
        self.value = []

    def method_one(self):
        d = utils.getProcessOutput('/bin/sh', ('-c', 'ls /home'))
        def set_self_value(result):
            print 'called set'
            self.value = 100
        d.addCallback(set_self_value)
        d.addCallback(self.method_two)

    def method_two(self, *args): # *args required to handle the result
        print 'called two'
        print self.value

def main():
    a = A()
    a.method_one()

reactor.callWhenRunning(main)
reactor.run()

Output:
called set
called two
100


text:
Q: How does long-distance space travel work in the MCU? In Guardians of the Galaxy vol. 2, we see long-distance space travel. It involves piloting your ship into some sort of "jump point" that opens up in space, taking the shape of a honeycomb-like structure with a single hex missing.
The way it's describe, these points are fixed in space: early in the movie, the Guardians have to out-run an enemy fleet to reach the one they need; later on, we see them fly through a very long series of them in sequence. It's also made clear that doing too many of these "jumps" in a row has consequences for the passengers.
The process seems to be similar to, say, the Mass Effect relay setup, mixed with a bit of Star Wars hyperspace travel.
Is this the first time we have seen long-distance space travel in the MCU? Is there anything from the source material that explains how this works from a logistical standpoint? If there's any information on the "science" behind it, that would also be helpful.

A: I'm not so sure about this but the space travel shown in the movie resembles the Stargates created in the Shi'ar Galaxy in the Marvel Comics. These are a network of devices that stabilize wormholes making intergalactic travel possible. In the comics, Xandar has this technology because of their alliance with the Shi'ar.


text:
Q: Merge two audio files(not concat) in Java(API)? I need to merge two audio files together. Basically place one audio file on top of another and make one file. I have seen some posts on concatenating two audio files, but none on this. Thanks for any help.

A: I recommend you take a look at JSyn.  I would discourage you to attempt to do it yourself, since it can get complicated with multiple audio formats.  It supports a lot more as well.

A: This worked for me. Use jresources.org to help you. You could use their example: http://www.jsresources.org/examples/MixingAudioInputStream.java.html. For the org.tritonus.share.sampled.TConversionTool package, if you have problems using their library, then download their source code (http://sourceforge.net/projects/tritonus/files/): it's open source, and try using it. I tried it and it worked for me :D. I'm grateful for those guys!


text:
Q: Problems with C files My code crashes,
Could you tell me what am i doing wrong?
if i isolate the FILE portion of the code it doesn't crash
#include <stdio.h>
#include <stdlib.h>
struct student
{
    char* name;
    char* dorm;
};
#define NUM 3

int main()
{
    struct student students[NUM];
    int i=0;
    for(i=0;i<NUM;i++)
    {
        char* naam;
        char* daarm;
        printf("Insert name of student #%d..\n",i+1);
        scanf("%s",&naam);
        students[i].name=naam;

        printf("Now enter name of the dorm\n");
        scanf("%s",&daarm);
        students[i].dorm= daarm;

    }

    FILE* file=fopen("C:/Users/Gigg/Desktop/ricchio.txt","w");
    if(file!=NULL)
    {
        int i;
        for(i=0;i<NUM;i++)
        {
            fprintf(file,"%s,%s",students[i].name,students[i].dorm);
        }

    }
    fclose(file);

    return 0;
}

i can't seem to find the answer anywhere,
furthermore,
the compiler also tells me that %s is expecting char* but that i give it char

A: Try the following.
Issues were

*

*Memory needed to be allocated.

*You were attempting to close file using a null pointer.

NOTE: Add an error message if file cannot be opened. Magically sized memory should be improved. Handle lengthy user input.
See my 'NOTE's.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>

struct student
{
    char name[1024]; // **NOTE**: magic number
    char dorm[1024]; // **NOTE**: magic number
};
#define NUM 3

int main()
{
    struct student students[NUM];
    int i=0;
    for(i=0;i<NUM;i++)
    {
      char naam[1024]; // **NOTE**: magic number
      bzero(naam, sizeof(naam));
      char daarm[1024]; // **NOTE**: magic number
      bzero(daarm, sizeof(daarm));

      printf("Insert name of student #%d..\n",i+1);
      scanf("%s",naam); // **NOTE**: input length
      strcpy(students[i].name,naam);

      printf("Now enter name of the dorm\n");
      scanf("%s",daarm); // **NOTE**: input length
      strcpy(students[i].dorm,daarm);
    }

    FILE* file=fopen("/tmp/test.txt",
                     "w");
    if(file!=NULL)
      {
        int i;
        for(i=0;i<NUM;i++)
          {
            fprintf(file,"%s,%s\n",students[i].name,students[i].dorm);
          }

        fclose(file); // **NOTE** should only be done if non-zero value.
    } else { // NOTE: error!!!
    }

    return 0;
}


text:
Q: Speed and transparency of light I have been puzzled with a fact that as an object moves faster, it ceases its property of opacity. I mean to say that as an object moves faster we can see right through it (more clearly than in a situation when his speed is low). Now with the fact that the speed of light has been controlled upto 61kmph in Bose-Einstein condensate, does it imply that light also becomes more and more opaque as its speed slower down?

A:
I have been puzzled with a fact that as an object moves faster, it ceases its property of opacity.

This is false.
Your example of a ceiling fan is flawed, what happens is that the fan is swapping places with the air. The air is transparent, but the fan isn't, and the constant swapping means that a portion of space is opaque only for a certain fraction of the time. This makes it appear as a mixture between transparent and opaque (this is due to persistence of vision).

Now with the fact that the speed of light has been controlled upto 61kmph in Bose-Einsteinian condensate, does it imply that light also becomes more and more opaque as its speed slower down?

Light is transparent. It does not interact in a uniform manner with other light waves so as to result in any absorption or reflection; so one does not "see" a light beam. (Unless it is shined directly at one's eyes)

A: Your principle that the motion of objects creates opacity is not correct. It's totally an optical (basically the vision-side) phenomenon called the persistence (as mentioned by John and Manish) - something very similar to the Wagon Wheel effect.
This is only because the object trace so fast through your field of view, that the series of images behind (the background) persist in your vision and look just like some animation. And for the same reason, the path traced by the fan blades look like a circular (more or less transparent) plates. Truly speaking, this phenomenon has a place in the animation movies. Have a look at their history...

To get deeper into this effect, we can use wavefronts. Recall the phrase: "every point in a wavefront maybe considered a source of secondary wavelets". Say, the wavefronts continuously emitted by the background are captured by our eyes. When some object is in between you and the background, only the wavefronts from that object reaches you (i.e) the object doesn't allow the background to be visible to you since it's opaque. Say, a new object traces through your view so that you're seeing its side (not towards or away). The wavefronts are emitted from different positions with respect to the background and hence they can interfere (mix-up) with that of the background. Actually, it's somewhat translucent.
Whatever... By this way, the object tricks you by making you believe that you're seeing some kinda transparency. This depends on how closer or farther the object is from you.
(except circular motions, it's somewhat complex)

Since your first theory is basically wrong, you can't say that these quantum objects are transparent because they're moving fast? - It's quite ridiculous (we can't see them at all). So, you can't expect these photons (the particle characterized to explain light) to be opaque when they're at rest (which they actually can't). If so, then arises a question, "If it causes opacity, what's the origin of light then?"
As for me, one can't see light at all such as reflection, refraction, interference, diffraction, scattering, polarization, etc... All that we see is based on every single property of light. There's no such thing as rays (theoretical parameter to explain optical effects through light paths) or beams (the word has origin only because light is scattered by the particles in its way).
Roughly, an object should be massive to create opacity in space. So, NO to both of your answers...


text:
Q: Game crashing after sharing post on facebook I am using fb.feed to share post on facebook within my game. It posts to my timeline successfully, but the game crashes. Here is what the log says :
 07-28 18:47:19.859: E/AndroidRuntime(27621): FATAL EXCEPTION: main
 07-28 18:47:19.859: E/AndroidRuntime(27621): Process:

com.blacksprite.pixelescape, PID: 27621
 07-28 18:47:19.859: E/AndroidRuntime(27621): java.lang.Error: FATAL EXCEPTION [main]

 07-28 18:47:19.859: E/AndroidRuntime(27621): Unity version     : 5.1.1f1
 07-28 18:47:19.859: E/AndroidRuntime(27621): Device model      : asus Nexus 7
 07-28 18:47:19.859: E/AndroidRuntime(27621): Device fingerprint: google/razor/flo:5.1.1/LMY48G/1965118:user/release-keys
 07-28 18:47:19.859: E/AndroidRuntime(27621): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64207, result=-1, data=Intent { (has extras) }} to activity {com.blacksprite.pixelescape/com.facebook.unity.FBUnityDialogsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.ActivityThread.access$1300(ActivityThread.java:151)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.os.Handler.dispatchMessage(Handler.java:102)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.os.Looper.loop(Looper.java:135)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.ActivityThread.main(ActivityThread.java:5254)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at java.lang.reflect.Method.invoke(Native Method)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at java.lang.reflect.Method.invoke(Method.java:372)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
 07-28 18:47:19.859: E/AndroidRuntime(27621): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.facebook.unity.FBUnityDialogsActivity$1.onComplete(FBUnityDialogsActivity.java:93)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.facebook.widget.FacebookDialog.handleActivityResult(FacebookDialog.java:372)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.facebook.UiLifecycleHelper.handleFacebookDialogActivityResult(UiLifecycleHelper.java:301)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.facebook.UiLifecycleHelper.onActivityResult(UiLifecycleHelper.java:165)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at com.facebook.unity.FBUnityDialogsActivity.onActivityResult(FBUnityDialogsActivity.java:77)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.Activity.dispatchActivityResult(Activity.java:6192)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
 07-28 18:47:19.859: E/AndroidRuntime(27621):     ... 10 more

A: Try updating the facebook unity SDK to beta and then try their example. If example is working fine then there is a issue in implementation.
https://developers.facebook.com/docs/unity/downloads


text:
Q: Apply a discount based on ACF field to cart total in WooCommerce I'm trying to create a discount programmatically for orders on my store. My users have a variable discount rate e.g. 10%. I want to apply their discount to the order before checkout, however, some items in the store are not applicable for a discount.
These items have a toggle set so I can check which products do or do not allow the discount to be applied.
Currently, I'm looping through the order to check which items are applicable and using a 'fixed_cart'coupon to add the discount.
This works, however, the in the admin the coupon applies to all line items even the items which should be skipped. Making it impossible to work how much to refund to customers when a refund is required.
Checking the cart items
$tradeDiscountTotal = 0;
foreach( WC()->cart->get_cart() as $cart_item ) {
    if(!get_field('trade_discount_exempt', $cart_item['product_id'])) {
        $tradeDiscountTotal += $cart_item['line_subtotal'];
    }
}

Applying the total discount for this order
$coupon->set_discount_type('fixed_cart');
$coupon->set_amount($tradeDiscountTotal);
return $coupon;

How can I create a bespoke discount for each order and ensure the products that are discounted are represented correctly in the admin area?

A: UPDATE
A solution is to create a coupon manually with a percentage discount with for example 10%.
Then we add the following codes based on the couponcode

*

*First part to ensure that a discount of 0 is applied to products that meet the condition

*Second part to ensure that the coupon is automatically added to the shopping cart

So we get:

*

*Discount amount on trade_discount_exempt = 0

function filter_woocommerce_coupon_get_discount_amount( $discount, $price_to_discount , $cart_item, $single, $coupon ) {
    // Product ID in cart
    $product_id = $cart_item['product_id'];

    // If 'trade_discount_exempt'
    if ( get_field( 'trade_discount_exempt', $product_id ) ) {
        $discount = 0;
    }

    return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );

*

*Apply coupon programmatically if NOT trade_discount_exempt in cart

function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

   if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Only cart
    if( ! is_cart() )
        return;

    // Coupon code
    $coupon_code = 'testcoupon';

    // Format
    $coupon_code = wc_format_coupon_code( $coupon_code );

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Product ID in cart
        $product_id = $cart_item['product_id'];

        // NOT 'trade_discount_exempt'
        if ( ! get_field( 'trade_discount_exempt', $product_id ) ) {
            // Applied coupons
            $applied_coupons = $cart->get_applied_coupons();

            // Is applied
            $is_applied = in_array( $coupon_code, $applied_coupons );

            // NOT applied
            if ( ! $is_applied ) {
                // Apply
                $cart->apply_coupon( $coupon_code );
                break;
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );

Optional: Here are 2 other possible solutions:
1. Use the woocommerce_calculated_total filter hook, apply a discount globally on cart
function filter_woocommerce_calculated_total( $total, $cart ) {
    // Discount (percentage)
    $percentage = 10; // 10 %

    // Set variable, used in loop
    $new_total = 0;

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Product ID in cart
        $product_id = $cart_item['product_id'];

        // NOT 'trade_discount_exempt'
        if( ! get_field( 'trade_discount_exempt', $product_id ) ) {
            // Product price
            $price = $cart_item['data']->get_price();

            // Caclulate new price
            $new_price = $price * ( 1 - ( $percentage / 100 ) );

            // Add new price to new total
            $new_total += $new_price;
        }
    }

    // New total greater than
    if ( $new_total > 0 ) {
        $total = $new_total;
    }

    return $total;
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );

2. Use the woocommerce_before_calculate_totals action hook, grant the discount on the product price
function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Discount (percentage)
    $percentage = 10; // 10 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Product ID in cart
        $product_id = $cart_item['product_id'];

        // NOT 'trade_discount_exempt'
        if( ! get_field( 'trade_discount_exempt', $product_id ) ) {
            // Product price
            $price = $cart_item['data']->get_price();

            // Caclulate new price
            $new_price = $price * ( 1 - ( $percentage / 100 ) );

            // Set price
            $cart_item['data']->set_price( $new_price );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );


text:
Q: Заполнить поля случайными данными в Mysql Есть простая таблица: id, name, text, image, date.
Как можно заполнить поля случайными данными (300 шт.) ?
Данные в полях (id, name, text, image, date) могут быть одинаковыми например: Название статьи, текст статьи, image.jpg, 1418939449.

A: Я бы предложил такой вариант:
Создать несколько массивов и в цикле заносить данные из них.
$rowsToCreate = 300;
$names = Array("name1", "name2", "name3", "name4");
$texts = Array("text1", "text2", "text3", "text4");
$images = Array("image1", "image2", "image3", "image4");
do {
    $sqlStr = "INSERT INTO [table] (name, text, image, date) VALUES ('" . array_rand($names) . "', '" . array_rand($texts) . "', '" . array_rand($images) . "', DATE_ADD(NOW(), INTERVAL 0-CAST(RAND()*100 AS SIGNED) DAY))";
    [запустить SQL]
    $rowsToCreate--;
} while ($rowsToCreate>=0);

Я не особенно понял почему date в формате int, а не, например bigint. В моем примере будет вставлена случайная дата в диапазоне от 100 дней назад до сейчас... Исправьте под нужное Вам.
Вообще все очень зависит от того, насколько безбашенными Вам нужны данные.
Можно имена генерировать простым md5() с выдергиванием цифр.
Тексты можно брать из какой-нибудь директории с txt файлами. Создать папку, накидать туда текстов из какой-нить библиотеки, и брать рандомно файлы.
Тоже самое можно сделать с картинками... Использоввать папку /Pictures (если Вы на винде)...
Много вариантов :)

A: https://github.com/fzaninotto/Faker
это не оно ?
я думаю самое распространенное решение


text:
Q: Tables with labeled lines I have a little question concerning the layout of tables. Does LaTeX provide a way to create tables like shown in the picture below?

I am referring to the two axes of the table that are labeled "K" and "n". Is there a way to have labeled axes in a table (with a little arrow at the end) instead of just having normal vertical and horizontal lines? Can I use the tabular environment or do I have to use something fancier?
Here is how my table would look without labeled axes:
\documentclass{scrartcl}

\begin{document}
  \begin{tabular}{l|cccc}
              & 0 & 1 & 2 & 3 \\ \hline
    $k_1 = 3$ & O & - & - & I \\
    $k_2 = 4$ & O & - & - & O \\
  \end{tabular}
\end{document}

Btw, does anybody know what those characters in the table in the screen caption above are? I approximated them with "I" and "O" but it doesn't look quite right.
I would be grateful for any help (and excuse my English, it's not my native tongue)!

A: A common tabular environment seems not appropriate for this kind of table. This is an approach with »PGF/TikZ« that draws a matrix with arrows between nodes where desired.
\documentclass[11pt,border=2pt]{standalone}
\usepackage[T1]{fontenc}
\usepackage{selinput}
\SelectInputMappings{
  adieresis={ä},
  germandbls={ß}
}
\usepackage{tikz}
\usetikzlibrary{calc,matrix,shapes.callouts}

\begin{document}
  \begin{tikzpicture}[
    thick,
    >=stealth,
    matrix of math nodes/.append style={execute at begin cell=\strut},
    note/.style={
      rounded corners,
      rectangle callout,
      inner sep=6pt,
      fill=#1,
      callout relative pointer={(-0.5,0.5)},
      font=\huge
    }
  ]
    \matrix (table) [
      matrix of math nodes,
      nodes in empty cells,
      nodes={
        anchor=center,
        inner sep=6pt,
        outer sep=0pt,
        minimum size=1.5em,
      }
    ] {
      ~~~~~~~~~ & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 \\
      k_1=2     & \bigcirc & - & | & - & - & - & - & - & - & - & - & - & - & - & - & - & - \\
                &   &   &   &   &   &   &   &   &   &   &    &    &    &    &    &    &    \\
      k_2=3_1   & \bigcirc & - & \bigcirc & | & - & | & - & - & - & - & - & - & - & - & - & - & - \\
                &   &   &   &   &   &   &   &   &   &   &    &    &    &    &    &    &    \\
      k_3=3_2   & \bigcirc & - & \bigcirc &   &   &   &   &   &   &   &    &    &    &    &    &    &    \\
                &   &   &   &   &   &   &   &   &   &   &    &    &    &    &    &    &    \\
      k_4=5     &   &   &   &   &   &   &   &   &   &   &    &    &    &    &    &    &    \\
      ~~~~~~~~~ &   &   &   &   &   &   &   &   &   &   &    &    &    &    &    &    &    \\
    };

    \draw[->] (table-2-1.north west) -- ($(table-2-18.north east)+(1em,0)$) node[right,font=\Large] {$K$};
    \draw[->] (table-1-1.north east) -- ($(table-9-1.south east)+(0,-1ex)$) node[below,font=\Large] {$n$};

    \foreach \i [evaluate=\i as \j using int(\i+3)] in {5,6,...,15}
      \draw[->] (table-2-\i.south) -- (table-4-\j.north);
    \foreach \c  in {8,9,...,18}
      \draw[->,dashed] (table-2-\c.south) -- (table-4-\c.north);
    \foreach \c  in {2,3,4}
      \draw[->,dashed] (table-4-\c.south) -- (table-6-\c.north);

    \node[note=blue!25,above left=1cm] at (table.south east) {Restliche Einträge analog \ldots};
  \end{tikzpicture}
\end{document}

I recommend to take a look at the user guide to get familiar with that package.
Regarding the symbols it's not entirely clear to me. I would interpret "O" as some kind of circle and the "I" as the pipe symbol ("|").


text:
Q: "Error occurred while executing the action getProviderAPIVersionUsage" When using wso2am-1.10.0 to create a new API using a SOAP endpoint, steps 3/3 completed and testing api just fine i /store. Yet, when coming back to /publisher clicking on the api gives an "API Publisher - Error" saying "Error occurred while executing the action getProviderAPIVersionUsage". wso2-apigw-errors.log contains only single type of error like this:

2016-08-10 14:35:43,004 [-] [pool-199-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614
  2016-08-10 14:35:46,466 [-] [pool-159-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614
  2016-08-10 14:35:47,079 [-] [pool-145-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614
  2016-08-10 14:35:47,367 [-] [pool-113-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614
  2016-08-10 14:35:47,485 [-] [pool-204-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614
  2016-08-10 14:35:54,322 [-] [pool-195-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614
  2016-08-10 14:35:54,346 [-] [pool-175-thread-1] ERROR AsyncDataPublisher Reconnection failed for for tcp://localhost:7614

A: According to your logs, it seems there is a connection issue. That's why this issue(error log you attached) has occurred. Similar issue can occur when DAS server startup has not completed when APIM starts. If you have enabled API Manager stats please check BAM/DAS configuration and connectivity to those nodes.
If you dont need stats and it enabled by accident you can revert that and try this again.


text:
Q: jQuery get children and give them numbers I need a jQuery function which should give children elements of a div differrent css attributes.

The divs inside the container are automatically generated.
the children of the Element should have this css attributes:
First child: animation-delay: 1s;

Second child: animation-delay: 2s;

Third child: animation-delay: 3s;

...
I´ve tried it with nth:child via css but it didnt work so I need a jQuery solution.

A: Really this needs no Javascript or jQuery. It's just not nth:child but :nth-child(n):

.container > :nth-child(1) {
  animation-delay: 1s;
  color: red;
}
.container > :nth-child(2) {
  animation-delay: 2s;
  color: blue;
}
.container > :nth-child(3) {
  animation-delay: 3s;
  color: green;
}
.container > :nth-child(4) {
  animation-delay: 4s;
  color: brown;
}

OOO

OOO

OOO

OOO

OOO

OOO

OOO

OOO

A: This adds the wanted css attribute:
$( ".container>div.autogenerated-div" ).each(function( index ) {
  $(this).css("animation-delay",(index+1)+"s");
});

Fiddle: https://jsfiddle.net/wxhrks0x/
Or do it with css less (without jQuery):
@iterations: 8;
.autogenerated-div-loop (@i) when (@i > 0) {
  .autogenerated-div-@{i} {
    animation-delay: ~"@{i}%"s;
  }
  .autogenerated-div-loop(@i - 1);
}
.autogenerated-div-loop (@iterations);

A: Works fine with nth-child

div.autogenerated-div:nth-child(1) {
  width: 20px;
  height: 10px;
  background-color: red;
  animation: newcolor 1s ease;
  animation-delay: 1s;
}

div.autogenerated-div:nth-child(2) {
  width: 20px;
  height: 10px;
  background-color: blue;
  animation: newcolor 1s ease;
  animation-delay: 2s;
}

div.autogenerated-div:nth-child(3) {
  width: 20px;
  height: 10px;
  background-color: green;
  animation: newcolor 1s ease;
  animation-delay: 3s;
}

@keyframes newcolor {
  to {
    background-color: black;
  }
}