text:
Q: Why in lumen in oauth_access_tokens.expires_at field does not work? In lumen app with dusterio/lumen-passport when new user is logged into the system
request like:
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "ey...",
"refresh_token": "de...5f0"

is returned and new row in "oauth_access_tokens" table is added with expires_at field and
also 1 more row in "oauth_refresh_tokens"
But when I tried to change manually value in oauth_access_tokens.expires_at field (I set prior date)
I expected that user will not have access ander this token, but it has access anyway...
Also checking sql tracing :
   SELECT *
    FROM `oauth_access_tokens`
    WHERE `id` = '336283f12e8c41d6c84a0f304191e93047ff5f6b349ad0e80c634460efb1e1d516d3e50f2d227f03' limit 1

in sql statements I do not see any checks on expires_at field...
Looks like that work a bit different I expected...
Also what for is "oauth_refresh_tokens" table and how can I use it ?
Making login I set days_to_expire parameter in LumenPassport  before token creation:
$days_to_expire =  30;
$tokens_expire_in = Carbon::now()->addDays($days_to_expire);

LumenPassport::tokensExpireIn($tokens_expire_in, $client_id);

$tokenRequest = $request->create('api/oauth/token'), 'POST');
$tokenRequest->request->add([
    "grant_type"    => "password",
    "username"      => $email,
    "password"      => $password,
    "client_id"     => $client_id,
    "client_secret" => $client_secret,
]);

$response = app()->handle($tokenRequest);

and tokens_expire_in that is the value I see in  oauth_access_tokens.expires_at field...
"dusterio/lumen-passport": "^0.3.4",
"laravel/lumen-framework": "^8.3.1",

Thanks!


text:
Q: Counter Not being changed Doing a project on a counter that can be changed by buttons, however the counter won't change. Chrome inspect element debug console thing isn't finding anything either.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Counter</title>

Counter

0

    <button onclick="decrease()" >Decrease</button>
    <button onclick="reset()" >Reset</button>
    <button onclick="increase()" >Increase</button>

A: Two things:

*

*You have to initalize counterNum to 0, otherwise its default value is undefined, which, when incremented, is NaN

*You are modifying the element's value, which does not affect the element's content. Instead, assign counterNum to the element's textContent or innerHTML.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Counter</title>

Counter

0

    <button onclick="decrease()" >Decrease</button>
    <button onclick="reset()" >Reset</button>
    <button onclick="increase()" >Increase</button>

A: Personally, I would use a constructor or class. Of course, you should use external CSS and JavaScript so it's cached. Here's my two cents:

//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, Counter; // for use on other loads
addEventListener('load', ()=>{ // reduce code you will reuse a lot
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id); mobile = /Mobi/i.test(nav.userAgent);
S = (selector, within)=>{
  let w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  let w = within || doc;
  return w.querySelectorAll(selector);
}
hC = (node, className)=>{
  return node.classList.contains(className);
}
aC = (node, ...classNames)=>{
  node.classList.add(...classNames);
  return aC;
}
rC = (node, ...classNames)=>{
  node.classList.remove(...classNames);
  return rC;
}
tC = (node, className)=>{
  node.classList.toggle(className);
  return tC;
}
Counter = function(start = 0, minLimit = -Infinity){
  this.count = start; this.minLimit = minLimit;
  this.increase = (by = 1)=>{
    this.count += by;
    return this;
  }
  this.decrease = (by = 1)=>{
    if(this.count > this.minLimit)this.count -= by;
    return this;
  }
  this.reset = (to = 0)=>{
    this.count = to;
    return this;
  }
}
// small library above - magic below can be put on another page using a load Event (except // end load line)
// get elements only once if you can
const counter = new Counter, counter_val = I('counter_val');
I('decrease').onclick = ()=>{
  counter_val.textContent = counter.decrease().count;
}
I('reset').onclick = ()=>{
  counter_val.textContent = counter.reset().count;
}
I('increase').onclick = ()=>{
  counter_val.textContent = counter.increase().count;
}
}); // end load
//]]>
/* css/external.css */
*{
  box-sizing:border-box;
}
html,body{
  width:100%; height:100%; margin:0;
}
h1,h2{
  margin:0;
}
.center{
  display:flex; justify-content:center; align-items:center; flex-wrap:wrap; width:100%; height:100%;
}
.center>*{
  width:100%; text-align:center;
}
<!DOCTYPE html>

    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Counter</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />

Counter

0

      <button id='decrease' type='button'>Decrease</button>
      <button id='reset' type='button'>Reset</button>
      <button id='increase' type='button'>Increase</button>

I removed your depreciated  tags. Of course, you've noticed that you need to initialize your counter to a Number, instead of undefined.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Emtpy Data of Column in Item when Workflow successfully Rejects or Approves I have created my own approval workflow.when Workflow successfully has done , i see Page content or Text Editor is Empty when Item copies to other library.i checked View Setting and Permission too.
See Picture here :
http://www.imagetoo.com/images/test2.jpg

A: Behrouz,
The problem is with the Copy List Item action of SharePoint Designer, see following post:
SharePoint Designer Copy List Item Workflow Activity Does Not Copy All Fields
I would suggest to Create a New Item in Rejected Idea list and set each field you need to propagate!
I hope this helps...


text:
Q: KVM inside Docker inside Hyper-V The use case is a Cuckoo sandbox, which is a way to test malware in an isolated environment. Cuckoo is running in a Docker container in a Ubuntu VM, which is in turn managed by Hyper-V.
Inside this Docker container, Cuckoo creates new Windows VMs using KVM "on the fly". It doesn't work.
When trying to manually start a Windows VM using this KVM inside a Docker container (using virsh start win7vm), these errors are displayed inside the Docker container:
> root@0a25149f706c:/var/log/libvirt# cat libvirtd.log 2019-11-05
> 10:54:56.137+0000: 5201: info : libvirt version: 4.0.0, package:
> 1ubuntu8.13 (Christian Ehrhardt <christian.ehrhardt@canonical.com>
> Wed, 21 Aug 2019 11:08:                           29 +0200) 2019-11-05
> 10:54:56.137+0000: 5201: info : hostname: 634d767f325e 2019-11-05
> 10:54:56.137+0000: 5201: error : virDBusGetSystemBus:109 : internal
> error: Unable to get DBus system bus connection: Failed to connect to
> socket /var/run/d                           bus/system_bus_socket: No
> such file or directory 2019-11-05 10:54:56.137+0000: 5201: error :
> dnsmasqCapsRefreshInternal:741 : Cannot check dnsmasq binary
> /usr/sbin/dnsmasq: No such file or directory 2019-11-05
> 10:54:56.210+0000: 5201: error : virFirewallValidateBackend:193 :
> direct firewall backend requested, but /sbin/ebtables is not
> available: No such file or d                           irectory
> 2019-11-05 10:54:56.210+0000: 5201: error : virFirewallApply:916 :
> internal error: Failed to initialize a valid firewall backend
> 2019-11-05 10:54:57.768+0000: 5201: error : virSysinfoReadX86:1032 :
> internal error: Failed to find path for dmidecode binary 2019-11-05
> 10:54:57.768+0000: 5201: error : virSysinfoReadX86:1032 : internal
> error: Failed to find path for dmidecode binary 2019-11-05
> 10:54:57.780+0000: 5201: error : virNodeSuspendSupportsTarget:336 :
> internal error: Cannot probe for supported suspend types 2019-11-05
> 10:54:57.780+0000: 5201: warning : virQEMUCapsInit:1224 : Failed to
> get host power management capabilities 2019-11-05 10:54:59.525+0000:
> 5201: error : virNodeSuspendSupportsTarget:336 : internal error:
> Cannot probe for supported suspend types 2019-11-05 10:54:59.525+0000:
> 5201: warning : umlCapsInit:76 : Failed to get host power management
> capabilities 2019-11-05 10:54:59.525+0000: 5201: error :
> virNetDevBridgeCreate:484 : error creating bridge interface virbr0:
> Operation not permitted 2019-11-08 13:19:45.472+0000: 59: info :
> libvirt version: 4.0.0, package: 1ubuntu8.13 (Christian Ehrhardt
> <christian.ehrhardt@canonical.com> Wed, 21 Aug 2019 11:08:29
> +0200) 2019-11-08 13:19:45.472+0000: 59: info : hostname: 0a25149f706c 2019-11-08 13:19:45.472+0000: 59: error :
> dnsmasqCapsRefreshInternal:741 : Cannot check dnsmasq binary
> /usr/sbin/dnsmasq: No such file or directory 2019-11-08
> 13:19:45.476+0000: 59: error : virFirewallValidateBackend:193 : direct
> firewall backend requested, but /sbin/ebtables is not available: No
> such file or dir                           ectory 2019-11-08
> 13:19:45.476+0000: 59: error : virFirewallApply:916 : internal error:
> Failed to initialize a valid firewall backend 2019-11-08
> 13:19:45.478+0000: 59: error : virSysinfoReadX86:1032 : internal
> error: Failed to find path for dmidecode binary 2019-11-08
> 13:19:45.478+0000: 59: error : virSysinfoReadX86:1032 : internal
> error: Failed to find path for dmidecode binary 2019-11-08
> 13:19:45.490+0000: 59: error : virNodeSuspendSupportsTarget:336 :
> internal error: Cannot probe for supported suspend types 2019-11-08
> 13:19:45.490+0000: 59: warning : virQEMUCapsInit:1224 : Failed to get
> host power management capabilities 2019-11-08 13:19:48.331+0000: 59:
> error : virSysinfoReadX86:1032 : internal error: Failed to find path
> for dmidecode binary 2019-11-08 13:19:48.770+0000: 59: error :
> virNodeSuspendSupportsTarget:336 : internal error: Cannot probe for
> supported suspend types 2019-11-08 13:19:48.770+0000: 59: warning :
> virLXCDriverCapsInit:90 : Failed to get host power management
> capabilities 2019-11-08 13:19:48.772+0000: 59: error :
> virNodeSuspendSupportsTarget:336 : internal error: Cannot probe for
> supported suspend types 2019-11-08 13:19:48.772+0000: 59: warning :
> umlCapsInit:76 : Failed to get host power management capabilities
> 2019-11-08 13:19:48.774+0000: 59: error : virFirewallApply:916 :
> internal error: Failed to initialize a valid firewall backend


text:
Q: Confused by the definition about the inertial frame of reference In Wikipedia, you can find the definition of the inertial frame of reference, which states:

In classical physics and special relativity, an inertial frame of reference (also inertial reference frame or inertial frame, Galilean reference frame or inertial space) is a frame of reference that describes time and space homogeneously, isotropically, and in a time-independent manner.

Actually, I don't think it's a good definition or a good description. So just like we define the equilibrium state in thermodynamics, can we propose a similar definition by comparison? I mean can we take three reference systems with different constant velocities and make a comparison between the corresponding state of motion and then give the definition of the inertial frame of reference?


text:
Q: Change "From" in outlook VBA Macro I have a macro in outlook that sends out email on its own using my personal email addres.  But I have another email which I have "send as" permission to, and want the macro to use that email address to send out emails. In the macro i have
objmail.to, objectmail.cc and objmail.bcc but i don't have objmail.from to hardcode the send email address. Is there anyway I can accomplish this.
 If ChkResolved = True Then
    If ChkEnglish = True Then
        If ChkLan = True Then
           objMail.To = "xxxx@test.com"
           objMail.Body = "Test" & vbNewLine & vbNewLine & Signature

         End If
    End If
 End If

A: you have to go for mailitem.SentOnBehalfOfName and put into their as string the Name of the Mailbox as displayed in outlook

A: If you are using Outlook 2007 or above then the MailItem.SendUsingAccount property provides this functionality.


text:
Q: CoreOS Cluster DNS setup I'm unsure of how to setup DNS for a coreos cluster.
Currently I have all of my api instances behind a haproxy load balancer and a DNS A record which points to the (elastic) ip of the load balancer. So I can send traffic to api.myapp.com and it gets routed to an api instance. This works fine but obviously the load balancer is a single point of failure.
If I move into setting up a cluster using coreos and the cluster is running multiple services-not just the api service- how do I point api.myapp.com to the cluster in the same way as I do currently, but ensure that any requests sent using this address are somehow routed only to the api service inside the cluster? This is something not clear to me from reading many tutorials on coreos.

A: You'll need to run a routing layer (HAproxy should work fine) that is directing traffic based on HTTP host header. Run this routing container on a few machines bound to 80/443 as desired. Add A records for each of your services that point to these few machines. Your LB is now highly available.
Next, set up your HAproxy routing rules to consume the location of your downstream services and route traffic appropriately. For example, a request to api.example.com gets routed to either 10.10.10.1, 10.10.10.2 or 10.10.10.3. The router (10.10.10.1:443) sees it has two backend containers responsible for api.example.com running on 10.10.10.99:9999 and 10.10.10.98:9898. The traffic is routed to one of the containers and the request is fulfilled.
A full example of this with Vulcan proxy and etcd is here: https://coreos.com/blog/zero-downtime-frontend-deploys-vulcand/


text:
Q: Obtain all possible combinations of logical variables without specifying the number of elements I'm trying to get all the combinations of a vector. I have
x <- c(1,2,3)

I need to get all the possible combinations without specifying the number of elements needed and without taking into account the order (the solution {2,3,1} is the same as {1,2,3}). For example, the result would be:
{}
{3}
{2}
{2,3}
{1}
{1,3}
{1,2}
{1,2,3}

An approximation would be to make the following table:

I am sure that there must be some function that performs this task instead of creating the table and forming the solutions from it, since it is not very tedious.

A: Use expand.grid
out <- expand.grid(rep(list(c(1, 0)), length(x)))
out
#  Var1 Var2 Var3
#1    1    1    1
#2    0    1    1
#3    1    0    1
#4    0    0    1
#5    1    1    0
#6    0    1    0
#7    1    0    0
#8    0    0    0

If we need the combinations - as a list - we might do
split(out * col(out), 1:nrow(out))
#$`1`
#[1] 1 2 3
#
#$`2`
#[1] 0 2 3
#
#$`3`
#[1] 1 0 3
#
#$`4`
#[1] 0 0 3
#
#$`5`
#[1] 1 2 0
#
#$`6`
#[1] 0 2 0
#
#$`7`
#[1] 1 0 0
#
#$`8`
#[1] 0 0 0

Or if we don't need the 0s we might do
by(out * col(out), 1:nrow(out), FUN = function(x) x[x != 0])

(by is short for lapply(split(... )


text:
Q: A Simple pthread_create causing 100% CPU usage in Qt When a simple Thread is run with just an infinite loop in it causing 100% CPU, how come is this possible?
My thread call is as follows on a QEvent in Qt dialog class, Say on a button click.
  pthread_t thread_id;
  pthread_create( &thread_id, NULL, DataCollectionThread, (void*) this );

And my thread procedure is,
void* DataCollectionThread( void* pParam )
{
   ((m_DataCollection*)pParam)->m_ReadDatafromport();
   return NULL;
}

And this ReadData() contains...
while(1)
{
}

My requirement is collecting data from serial port and plot a graph continuously. But as the CPU usage is 100%, any hardware interrupt in between plotting cause the plotting to stall, as the CPU switches the task to handle interrupt.
I am calling this thread in a Qt::Dialog based class. I am pretty sure that nothing other than this is triggered. What's wrong with this? Does a simple infinite loop causes 100% CPU consumption eh? Or Is there any problem with using pthread_create in Qt?
EDIT:For Jonathon Reinhart
This is the actual while loop
while( 1 )
    {

            while(( Dataisavailable))
            {
                 //push the read data to stack
            }

        if(!m_DataReadable)
            break;
      }

A: Unlike cooperative multitasking, true OS-supported threads allow the CPU to interrupt code that's locked like this.  So your computer isn't completely dying.  But some degradation will occur.  The computer doesn't have a good way of knowing not to try its best to run the code it's given if there is work to do...short of scheduling tools like nice
Sometimes you can mitigate the problems caused by something like this with "thread priorities".  Qt has a QThread::setPriority() abstraction but note that it says:

The effect of the priority parameter is dependent on the operating system's scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler for more details).

Seems the Qt people looked at thread priorities under linux and gave up.  So if that's your platform, then you likely should just design your system so it doesn't spin like this.
I'd be curious what happened if you change ReadData() to...
QMutex dummy;
while(1)
{
    QMutexLocker locker (&dummy);
}

(which was my way of trying something that may be more effectively done with the sched_yield that @jweyrich just mentioned.)

A: YES.
while(1) { }

Is going to do the following:
1. Does the number 1 equate to true?
2. Yes.
3. Go to 1.

The CPU is going to continuously do this whenever that thread is executing. Why are you starting a thread just to put it in a spin loop that does nothing?

A: One simple hack to get around this:  Go to sleep for (short) periods to let the CPU do other stuff.  #include <ctime> and add somewhere in your loop:
struct timespec ts;
ts.tv_sec=0;
ts.tv_nsec=10000000; // 10 milliseconds
nanosleep(&ts, NULL);

Of course, it would be better if you could explicitly sleep until you have actual work to do (more input to read, a full queue to trim).  But adding in short sleeps will probably be sufficient.
It might make sense to look into your m_pDataProvider object's implementation.  Check for or add a method allowing you to sleep until there's more data.  If you're just reading from a character device (e.g. ttyS0), poll or select might be useful here.


text:
Q: How to setup phone Volumes on iOS? The volume of media, phone call, etc.. are different I would like to control volumes of iPhone. (The volume of media and phone call are not same.)
I'v searched a lot. All of them are just told me use MPVolumeView to control volume. I got an information that using MPVolumeView is one way and it can't setup multi-volume one time. But it's old(2014). So, I'm not sure is any new idea for this.
I'v tried to setup different volume. The first one is media volume. The other is Phone call volume. They are not same. I exactly there are two volumes on iOS.

Please help or try to give some ideas how to achieve this. Thanks!


text:
Q: How to restore Active Desktop if Themes is locked via GPO? My company forces Active Desktop upon everybody so that it can display a (monthly-rotated) corporate wallpaper.jpg.
Problem is, some computers (including my laptop) somehow experienced some errors resulting in the dreaded "Active Desktop Recovery" screen to show up... and clicking the "Restore My Active Desktop" button always resulted in "Internet Explorer Script Error".
Various workarounds I found in the Internet either does not work or requires me to change the theme first to something else... and the latter I can't do because the Desktop Settings screen is locked via GPO.
As it happens, due to the nature of the programs I use, I'm granted Administrator-level access on my computer.
The question is:
How do I fix my situation?
Note: I don't need to put on my own wallpaper, but watching the "Active Desktop Recovery" screen gets tiresome. I'm quite happy with the corporate wallpaper. I just need to somehow 'recover' my Active Desktop.
More information:

*

*OS: Windows XP Professional SP3 (yeah, company's too afraid to even experiment with Windows 7)

*Antivirus: Symantec Endpoint Protection

If you need any additional information, feel free to ask.

A: Being this is a GPO issue have you thought about just asking IT to fix it? Being domain admins they can do things like temporarily turn off your GPO rules and get it fixed a lot easier than you your self could.
I know as a techy myself it can be hard to just ask somone else to fix something for you on your computer, but sometimes you just got to go IT and get stuff fixed.

A: Workaround: Right click anywhere on the desktop, choose Properties.
On the Desktop tab, just click a different Background then click the original (corporate) one.
Windows will think you made a change (although you didn't) so the Apply button becomes active. Hit it (or the OK button), message will be gone.
Other (suggested) solution: Open Regedit, drill down to HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Desktop\Components and set the value for DeskHtmlVersion to 0.
That last one didn't work for me because after a restart (or logout/login), the value was back to 0x00000110 (272).
Do you have your system set to automatically log you in? I do, and see the white screen occasionaly, too.. maybe twice a week. If you really need the auto-logon, use the workaround above (just 6 mouse clicks).


text:
Q: Android gradle flavors, sourceset per flavor with multiple srcDirs, force overriding of values/strings.xml This question is a follow up of Android gradle library resources in product flavor
Came up with a strange issue.
Namely as described in Android gradle library resources in product flavor when using multiple source sets for each flavor, for res and resources everything works fine, the resources from other directories are merged all together.
Problem:
The flavor values/strings.xml won't replace the values/strings.xml in the main project
(This is where i keep the app label and app icon).Because of this behaviour my app icon and title are messed up (not from the flavor).
I found something here: http://tools.android.com/tech-docs/new-build-system/resource-merging
(title Handling Multiple Resource Folders) but that does not help me to go further as I don't understand how to force this specific flavor file to override the other in main project.
== Edit ==
My project structure and build.gradle (for the main project)
Project structure

*

*3rdparty

*

*Graphics

*

*Iconsets

*

*IconsetBase

*Iconset1

*Iconset3

*MainProject

*

*src

*

*main    (main project)

*flavor1

*flavor2

*...

build.gradle (main project)
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        repositories {
            mavenCentral()
        }
        classpath 'com.android.tools.build:gradle:0.10.0'
    }
}

apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    useOldManifestMerger false
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    lintOptions {
       ...
    }

sourceSets {
    main.java.srcDirs = ['src/main/java']
    main.resources.srcDirs = ['src/main/res']
}

signingConfigs {
    ...
}

buildTypes {
    ...
}

// Common dependencies
dependencies {
   compile project(':3rdparty:Graphics:Iconsets:IconsetBase')
}

defaultConfig {
    ...
}

productFlavors {
    flavor1         { packageName "..."}
    flavor2         { packageName "..."}
}

android.sourceSets.flavor1 {
    res {
        srcDirs = ['flavor1','../3rdparty/Graphics/Iconsets/IconsetBase/src/main/res', '../3rdparty/Graphics/Iconsets/Iconset1/src/main/res']
    }
    resources {
        srcDirs = ['flavor1','../3rdparty/Graphics/Iconsets/IconsetBase/src/main/res', '../3rdparty/Graphics/Iconsets/Iconset1/src/main/res']
    }
}
android.sourceSets.flavor2 {
    res {
        srcDirs = ['flavor2','../3rdparty/Graphics/Iconsets/IconsetBase/src/main/res', '../3rdparty/Graphics/Iconsets/Iconset3/src/main/res']
    }
    resources {
        srcDirs = ['flavor2','../3rdparty/Graphics/Iconsets/IconsetBase/src/main/res', '../3rdparty/Graphics/Iconsets/Iconset3/src/main/res']
    }
}
}

dependencies {
    compile 'com.android.support:support-v4:19.1.0'
    compile 'com.android.support:appcompat-v7:19.1.0'
    compile 'com.google.android.gms:play-services:4.3.23'
}

SOLVED
Issue was with the MainProject.iml
After adding flavor paths to RES_FOLDERS_RELATIVE_PATH everything worked


text:
Q: Does duplicate Dependency affect APK size? This site helps you in finding the methods count of a gradle library.
It shows you the number of methods of a library and also the number of methods of all dependencies used in that library. like:

As the dependencies used by a library increase DEX size like shown in above screenshot.

If we are using a dependency in our project, which is also used by
  another library. Will it increase the DEX size twice?
If yes, can we overcome this?

A:
If we are using a dependency in our project, which is also used by another library. Will it increase the DEX size twice?

Gradle manages the dependencies for you.
It doesn't download the same library twice and doesn't add the dependency twice.


text:
Q: Running my Junit Tests in Terminal I just started to work with JUnit. I ran my test through Intelij IDEA and it is all fine but when I'm trying to run my test in terminal using this code:
java -cp /junit4.10/junit-4.10.jar:. /Users/maidini/IdeaProjects/HelloWorld/test/CalculatePriceTest.java

I am getting this error :
Exception in thread "main" java.lang.NoClassDefFoundError: /Users/maidini/IdeaProjects/HelloWorld/test/CalculatePriceTest/java
Caused by: java.lang.ClassNotFoundException: .Users.maidini.IdeaProjects.HelloWorld.test.CalculatePriceTest.java
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Do you have any idea what should I do to be able to successfully run my test in terminal as well? I am using Mac Lion as well.

A: You first have to compile your code using javac; loading .java source files on your classpath won't work. Remember to add both your unit test class, and the actual class that you're testing. And any dependencies they might have. Maybe you'll want to bundle them in a .jar file, too, so your command-line won't get too long. Also, don't forget to recompile every time you change your code or your test.
This can get hairy pretty quickly. Instead, I recommend you use a build tool, like Maven. With a proper Maven build, you can just type mvn test, and Maven will handle the dependencies, compilation, and running the tests for you.
If you don't want to use Maven, you could also look into Ant (preferably in combination with Ivy), or Gradle, or any other Java build tool.


text:
Q: Component not reloading but state is changing with useState I'm not new to react, but im new using hooks, today I was playing with an array of selected elements and selection/unselection.
If they are selected then one icon is shown, if not, another icon (I just change the name prop, not the component itself.
The console.log I do every render shows the right results, but it is not working as expected on the JSX.
The render seems to only reload (Show the right icon) when I unselect. Explaining as a list the procedure and my problem:

*

*All elements come selected

*I unselect one element (remove from list), the icon changes.

*I select back the element (add to list), the icon don't change.

*I unselect another element, then it works and the components are
reloaded

Here is my object array:
const dies = [
  {
    id: 1,
    nomDia : 'Dies',
    dataDia : 'previs'
  },
  {
    id: 2,
    nomDia : 'Dies',
    dataDia : 'previs'
  },
  {
    id: 3,
    nomDia : 'Dies',
    dataDia : 'previs'
  }
]

Here is the useSate declaration:
const [diesSeleccionats, setDiesSeleccionats] = useState(dies)

Here is the functions that check if is selected and the function that adds/removes from selected list:
// check if selected
const estaSeleccionat = (dia) => {
    return diesSeleccionats.findIndex((aDia) => aDia.id === dia.id ) != -1
  }
// remove selected or add selected
const gestionarSeleccionats = (dia) => {
    if(estaSeleccionat(dia)){
      return diesSeleccionats.filter((aDia) => aDia.id !== dia.id)
    } else {
      diesSeleccionats.push(dia)
      return diesSeleccionats
    }
 }

Here is the component:
   dies.map((dia) => (
                      <View key={dia.id} style={{flexDirection: 'row', marginTop: 5, alignSelf: 'flex-end'}}>
                        <TouchableOpacity
                          style={{backgroundColor: Colors.llistat1 + 'CC'}}
                          key={dia.id}
                          onPress={() => setDiesSeleccionats(gestionarSeleccionats( dia ))}
                        >
                            <Text style={{fontSize: 18, color: Colors.titolsPantalles}}> {dia.nomDia} </Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                          style={{
                            minWidth: 24,
                            backgroundColor: Colors.llistat1 + 'CC',
                            marginLeft: 5,
                            paddingHorizontal:5,
                            justifyContent:'center', alignItems: 'center'}}
                          onPress={ () => setDiesSeleccionats(gestionarSeleccionats( dia ))}
                          >
                          <Ionicons name={ estaSeleccionat( dia ) ? "md-checkmark" : "md-close"} size={18} color={Colors.titolsPantalles} />
                        </TouchableOpacity>
                      </View>
                    ))

You can see than <Ionicons> name comes defined by if the element is on the selected list.
The log I do every re-render shows the right results. (Boolean of the check function, and the right elements on the array of objects)
Thanks.

A: I think the issue is related to mutating diesSeleccionats instead of copying it. I think you need to make a copy of it to provide to setDiesSeleccionats so React can analyze the differences and render the correct updated state.
const gestionarSeleccionats = (dia) => {
    const selections = [...diesSeleccionats];
    if(estaSeleccionat(dia)){
      return selections.filter((aDia) => aDia.id !== dia.id);
    } else {
      selections.push(dia)
      return selections;
    }
 }


text:
Q: How to read lines of data from multiple files I need to extract data from files in directory /tmp/log.
I have no problem extract from single file.
#!/bin/bash
while read line;
do
  echo $line
done < /tmp/log/file1

I want try it with multiple files /tmp/log/* but it returned error ambiguous redirect.
Any idea how can I around it?

A: You could read the files in a for loop as follows:
for file in /tmp/log/*; do
    while read -r line; do
        echo "$line"
    done < "$file"
done

The strategy is just wrap your while loop with a for loop that takes care of processing each of the files one at a time.

A: Dont know exactly waht you need..
probably you are looking for this:
cat /tmp/log/*

Is this what you need?
for line in `cat /tmp/log/*`
do
echo $line
done


text:
Q: Position jQuery dialog box I've tried a million solutions and none seem to work. I just need to push my jQuery dialog box about 50px from the top of the page. Any ideas how?
function message() {
    $("#message").dialog({
      title: 'Title here',
      draggable:false,
      minHeight:100,
      resizable: false
    });
 }

A: There's a position parameter for that, it accepts an array with X and Y coordinates :
function message() {
    var myPos = [ $(window).width() / 2, 50 ];

    $("#message").dialog({
      title: 'Title here',
      draggable:false,
      minHeight:100,
      position: myPos,
      resizable: false
    });
}

FIDDLE

A: Like adeneo mentioned, dialog has a position option which accepts a few data types, including jQuery-UI's fancy position object.
Given all the options, I think the cleanest and clearest way to specify the position you want is like this:
var myPos = { my: "center top", at: "center top+50", of: window };

Try it in jsFiddle

A: Have you tried this? css code .myPosition
.myPosition {
    position: absolute;
    top: 20px;
}

and jquery
$('.selector').dialog({ dialogClass: 'myPosition' });


text:
Q: Extend data.frame class in R to inherit data.frame methods I am having trouble defining a class that inherits all of a data.frame's methods. For example, if I was to define a class timeline this could be represented as a data.frame:
data.frame(task = c("Read Permutation City", "Learn S4 oop"),
           from = c(Sys.Date(), Sys.Date()),
           to = c(Sys.Date() + 5, Sys.Date() + 1))

Instead I would like to define a class "timeline" that would retain all of a data.frames methods but override and add several methods (e.g. plot, summary and window). In other languages this is fairly straightforward.
I would like to do this using an S4 class structure. I tried to implement an S4 class using the contains argument, however, I must be doing something wrong as the results are not what you expect from a data.frame.
timeline <- setClass(Class = "timeline", contains = "data.frame")

timeline <- function(task, from, to) {
  new("timeline", data.frame(task = task, from = from, to = to))
}

tm <- timeline("Run", Sys.Date(), Sys.Date() + 5)
getClass("timeline") # Class "timeline" .... Extends: Class "data.frame", directly
inherits(tm, "data.frame") # TRUE

nrow(tm) # 0
ncol(tm) # 3

tm # Prints S4 info
print(tm) # Expected output

What is the right way of doing this?

A: use setOldClass("data.frame") before setClass().


text:
Q: grpc header/cookie in Go I want to do place on server application which can be called by Go APP and Java app both.
for some reason ,there's a cookie authentication and oAuth mechanism ,so I want to set one Go app as  Auth Micro-service for the authentication purpose.
As GRPC is built on the HTTP2 ,so The headers and cookies are on the protocol.but I did not find out how to carry on header and cookie when the rpc occurs,implemented by Go, on GitHub I only found the JAVA-Implementation for headers at :
https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples/header

Can anybody give me some direction of Go implementation for this purpose?

A: Headers in gRPC are called "Metadata." Clients can only send "headers". Servers can send both "headers" and "trailers."
You want to:

*

*Use the google.golang.org/grpc/metadata package and metadata.NewContext() to send metadata from the client-side.

*Use grpc.SendHeader() and grpc.SetTrailer() to send metadata from the server-side.

*Use the grpc.Header() and grpc.Trailer() CallOptions for receiving the Metadata on the client-side.

*Use metadata.FromContext() for receiving metadata on the server-side.


text:
Q: How to upload images using an API Key that gives you permission to upload? [Python source code included] The documentation of the API shows source code on how to accomplish this in Python:
#!/usr/bin/python

import pycurl

c = pycurl.Curl()
values = [
          ("key", "YOUR_API_KEY"),
          ("image", (c.FORM_FILE, "file.png"))]
# OR:     ("image", "http://example.com/example.jpg"))]

c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)

c.perform()
c.close()

I'd like a bit of guidance on how to do this in C#. For instance, I'm lost on what these "values" would be in C#, how would I even declare them?
I'm not familiar with cURL at all, so that might be holding me back from translating a bit.
Help me Obi-wan. You're my only hope. /click

A: You just need to perform an HTTP POST, e.g. this code with a "parameters" string of key=YOUR_API_KEY&image=http://example.com/example.jpg or the like.


text:
Q: How can I configure jetty to use my jersey servlet with HTTPS protocol Please help me.
I readed on http://wiki.eclipse.org/Jetty/Howto/Configure_SSL, that I need to configure $Jetty_Home/etc/jetty.xml and specify my keystore
<Call name="addConnector">
  <Arg>
    <New class="org.eclipse.jetty.server.ssl.SslSelectChannelConnector">
      <Arg>
        <New class="org.eclipse.jetty.http.ssl.SslContextFactory">
          <Set name="keyStore"><SystemProperty name="jetty.home" default="." />/etc/keystore</Set>
          <Set name="keyStorePassword">OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4</Set>
          <Set name="keyManagerPassword">OBF:1u2u1wml1z7s1z7a1wnl1u2g</Set>
          <Set name="trustStore"><SystemProperty name="jetty.home" default="." />/etc/keystore</Set>
          <Set name="trustStorePassword">OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4</Set>
        </New>
      </Arg>
      <Set name="port">8443</Set>
      <Set name="maxIdleTime">30000</Set>
    </New>
  </Arg>
</Call>

But I don't understand how to specify that my jersey servlet needs to use https
may be it needs to specify in web.xml?
Here is my souce code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
@Path("/")
public class Uploader {

        //post method
    @POST
        //full path is: https://localhost:8443/loguploadservice/uploader
    @Path("/uploader")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces("text/plain")
    public Response upload(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail) {

        String uploadedFileLocation = "d://uploaded/"
            + fileDetail.getFileName();

        // save it
        writeToFile(uploadedInputStream, uploadedFileLocation);

        String output = "File uploaded to : " + uploadedFileLocation;

        return Response
                .status(200)
                .entity(output).build();

    }
        /**
        *write data to file
        */
    private void writeToFile(InputStream uploadedInputStream,
        String uploadedFileLocation) {

         try {
            OutputStream out = new FileOutputStream(new File(
                    uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            out.flush(); //flush data
            out.close(); //close output stream
            uploadedInputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        }
  }


text:
Q: Jaxb default to infinity I'm trying to make a XML Schema with Jaxb to represent the parameters for a number picker/spinner:  min, max and step. I want to have max default to infinity, min to negative infinity, and step default to Double.MIN_VALUE.
Both infinity and negative infinity are valid xml and double values, so it seems like their should be a way to have it default to them. Bonus points if their a shortcut to Double.MIN_VALUE other than just copying that number.
Currently I have:
  <xsd:element name="NumericParameter">
    <xsd:complexType>
      <xsd:complexContent>
        <xsd:extension base="batsignal:DetectorParameter" >
          <xsd:sequence>
            <xsd:element name="min" type="xsd:double" default="-INF"/>
            <xsd:element name="max" type="xsd:double" default="+INF" />
            <xsd:element name="step" type="xsd:double" default="0x0.0000000000001P-1022" />
          </xsd:sequence>
        </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
  </xsd:element>

And I get:
org.xml.sax.SAXParseException; lineNumber: 173; columnNumber: 72; e-props-correct.2: Invalid value constraint value '+INF' in element 'max'.
    at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
    at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:135)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
    at java.xml/com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4214)
...

Thanks!

A: According to w3.org INF or -INF are accepted values. No mention of +INF.

The special values positive and negative infinity and not-a-number have lexical representations INF, -INF and NaN, respectively. Lexical representations for zero may take a positive or negative sign.

For example, -1E4, 1267.43233E12, 12.78e-2, 12 , -0, 0 and INF are all legal literals for double.

UPDATE (credit to @Michael-Kay):

+INF becomes a valid value in XSD 1.1.

See his answer.


text:
Q: How to extern SDL_Surface array in C? I want to extern a SDL_Surface array from one function (load_level) to another (initialize_balls). I have to say that the SDL_Surface (brickim) is a dynamic pointer-struct which is defined inside of load_level function via malloc function and declared as SDL_Surface **brickim as well. I got a segmentation fault when I try to access brickim[0]->w in the initialize_balls function but not in the load_level function. This is the piece of code I hope you could help me to fix.
file1.c
#include <stdio.h>
#include <SDL.h>
SDL_Surface **brickim; /*as global*/
SDL_Surface* load_map(char *map_name , int tran );

void load_level(int stage){
int n;
SDL_Surface **brickim=( SDL_Surface **)malloc(sizeof(SDL_Surface)*input.N);
    for (n=0;n < input.N;n++){
        **brickim[n]=load_map("brick1.bmp",1); /*load SDL_Surfaces*/**
        printf("%d\n",brickim[n]->w);  /***access succesfully (returns 100 N times)***/
        }
...
}}
SDL_Surface* load_map(char *map_name , int tran ){
SDL_Surface *temp,*map;
Uint32 colorkey;
        printf("Loading bit map %s %d...\n",map_name,tran);
        temp = SDL_LoadBMP(map_name);
        if (temp == NULL){
                printf("Unable to load bitmap: %s\n", SDL_GetError());
                SDL_FreeSurface(temp);
                exit(0);
        }else{
                map = SDL_DisplayFormat(temp);
                colorkey = SDL_MapRGB( map -> format, 132, 0, 12);
                if ( tran==1 ) SDL_SetColorKey( map, SDL_SRCCOLORKEY, colorkey );
                SDL_FreeSurface(temp);
        }
                return map;
 }

file2.c
#include <SDL.h>
#include <stdlib.h>
#include <stdio.h>

extern SDL_Surface **brickim;/*brings brickim to this function*/

void initialize_balls()
{
      printf("Into initialization :)\n ");
    printf("%d \n",brickim[0]->w); /***returns segmentation fault***/
}

$./kuranes
Loading bit map brick1.bmp 1...
level image:) 100 (x10 times)
Into initialization :)
Violación de segmento (`core' generado)

Everything was running ok when I used a single SDL_Surface compiled with gcc but I need to do it dynamically. I think something very basic is missing.

A: Your problem seems to be here. You declare a global brickim, this will be what the extern declaration finds. You then, in load_level, declare a local brickim variable. You can declare a variable with the same name in different scopes, but the global brickim will not be used within load_level, the local one will. Therefore, while you do malloc into the local brickim, you don't ever assign into the global brickim - and therefore if you access it via extern, it will be NULL and you'll segfault.
SDL_Surface **brickim; /*as global*/
SDL_Surface* load_map(char *map_name , int tran );

void load_level(int stage){
int n;
SDL_Surface **brickim=( SDL_Surface **)malloc(sizeof(SDL_Surface)*input.N);
    for (n=0;n < input.N;n++){
        **brickim[n]=load_map("brick1.bmp",1); /*load SDL_Surfaces*/**
        printf("%d\n",brickim[n]->w);  /***access succesfully (returns 100 N times)***/
        }
...
}}

edit: you might want to check that whole allocation in general. I'm not familiar with the SDL_Surface struct, but i assume it's not a pointer type (it's a generic struct). Your allocation is actually allocating N structures, but you're casting as if you're allocating N pointers to SDL_Surface structures. Don't cast malloc.
If you want N SDL_Surface structures, you only need to have:
SDL_Surface * brickim = malloc(sizeof(SDL_Surface) * N)

If you want N pointers to SDL_Surface structures, you would need:
SDL_Surface ** brickim = malloc(sizeof(SDL_Surface *) * N)
for( i = 0; i < N; i++){
   // you've only allocated an array of pointers so far, you now need
   // allocate N structures
   brickim[0] = malloc(sizeof(SDL_Surface));
}


text:
Q: How to make modifications work without restarting MySQL? I deleted the slow.log of MySQL,but seems it's still cached in the system.
But I don't want to restart MySQL.

A: Have you tried flush logs;?  Flush logs "closes and reopens all log files."


text:
Q: OpenMP Dynamic vs Guided Scheduling I'm studying OpenMP's scheduling and specifically the different types.  I understand the general behavior of each type, but clarification would be helpful regarding when to choose between dynamic and guided scheduling.
Intel's docs describe dynamic scheduling:

Use the internal work queue to give a chunk-sized block of loop
  iterations to each thread. When a thread is finished, it retrieves the
  next block of loop iterations from the top of the work queue. By
  default, the chunk size is 1. Be careful when using this scheduling
  type because of the extra overhead involved.

It also describes guided scheduling:

Similar to dynamic scheduling, but the chunk size starts off large and
  decreases to better handle load imbalance between iterations. The
  optional chunk parameter specifies them minimum size chunk to use. By
  default the chunk size is approximately loop_count/number_of_threads.

Since guided scheduling dynamically decreases the chunk size at runtime, why would I ever use dynamic scheduling?
I've researched this question and found this table from Dartmouth:

guided is listed as having high overhead, while dynamic has medium overhead.
This initially made sense, but upon further investigation I read an Intel article on the topic.  From the previous table, I theorized guided scheduling would take longer because of the analysis and adjustments of the chunk size at runtime (even when used correctly).  However, in the Intel article it states:

Guided schedules work best with small chunk sizes as their limit; this
  gives the most flexibility. It's not clear why they get worse at
  bigger chunk sizes, but they can take too long when limited to large
  chunk sizes.

Why would the chunk size relate to guided taking longer than dynamic?  It would make sense for the lack of "flexibility" to cause performance loss through locking the chunk size too high.  However, I would not describe this as "overhead", and the locking problem would discredit previous theory.
Lastly, it's stated in the article:

Dynamic schedules give the most flexibility, but take the biggest
  performance hit when scheduled wrong.

It makes sense for dynamic scheduling to be more optimal than static, but why is it more optimal than guided?  Is it just the overhead I'm questioning?
This somewhat related SO post explains NUMA related to the scheduling types.  It's irrelevant to this question, since the required organization is lost by the "first come, first served" behavior of these scheduling types.
dynamic scheduling may be coalescent, causing performance improvement, but then the same hypothetical should apply to guided.
Here's the timing of each scheduling type across different chunk sizes from the Intel article for reference.  It's only recordings from one program and some rules apply differently per program and machine (especially with scheduling), but it should provide the general trends.

EDIT (core of my question):

*

*What affects the runtime of guided scheduling?  Specific examples?  Why is it slower than dynamic in some cases?

*When would I favor guided over dynamic or vice-versa?

*Once this has been explained, do the sources above support your explanation?  Do they contradict at all?

A:
What affects the runtime of guided scheduling?

There are three effects to consider:
1. Load balance
The whole point of dynamic/guided scheduling is to improve the distribution of work in the case where not each loop iteration contains the same amount of work. Fundamentally:

*

*schedule(dynamic, 1) provides optimal load balancing

*dynamic, k will always have same or better load balancing than guided, k
The standard mandates that the size of each chunk is proportional to the number of unassigned iterations divided by the number of threads in the team,
decreasing to k.
The GCC OpenMP implemntation takes this literally, ignoring the proportional. For example, for 4 threads, k=1, it will 32 iterations as 8, 6, 5, 4, 3, 2, 1, 1, 1, 1. Now IMHO this is really stupid: It result in a bad load imbalance if the first 1/n iterations contain more than 1/n of the work.

Specific examples? Why is it slower than dynamic in some cases?

Ok, lets take a look at a trivial example where the inner work decreases with the loop iteration:
#include <omp.h>

void work(long ww) {
    volatile long sum = 0;
    for (long w = 0; w < ww; w++) sum += w;
}

int main() {
    const long max = 32, factor = 10000000l;
    #pragma omp parallel for schedule(guided, 1)
    for (int i = 0; i < max; i++) {
         work((max - i) * factor);
    }
}

The execution looks like this1:

As you can see, guided does really bad here. guided will do much better for different kinds of work distributions. It is also possible to implement guided differently. The implementation in clang (which IIRC stems from Intel), is much more sophisticated. I truely do not understand the idea behind GCC's naive implementation. In my eyes it effectively defeates the purpose of dynamic load blancing if you give 1/n work to the first thread.
2. Overhead
Now each dynamic chunk has some performance impact due to accessing shared state. The overhead of guided will be slightly higher per chunk than dynamic, as there is a bit more computation to do. However, guided, k will have less total dynamic chunks than dynamic, k.
The overhead will also depend on the implementation, e.g. whether it uses atomics or locks for protecting the shared state.
3. Cache- and NUMA-effects
Let's say write to a vector of integers in your loop iteration. If every second iteration was to be executed by a different thread, every second element of the vector would be written by a different core. That's really bad because by doing so, they compete cache-lines that contain neighbouring elements (false sharing). If you have small chunk sizes and/or chunk sizes that don't align nicely to caches, you get bad performance at the "edges" of chunks. This is why you usually prefer large nice (2^n) chunk sizes. guided can give you larger chunk sizes on average, but not 2^n (or k*m).
This answer (that you already referenced), discusses at length the disadvantage of dynamic/guided scheduling in terms of NUMA, but this also applies to locality/caches.
Don't guess, measure
Given the various factors and difficulty to predict specifics, I can only recommend to measure your specific application, on your specific system, in your specific configuration, with your specific compiler. Unfortunately there is no perfect performance portability. I would personally argue, that this is particularly true for guided.

When would I favor guided over dynamic or vice-versa?

If you have specific knowledge about the overhead / work-per-iteration, I would say that dynamic, k gives you the most stable results by chosing a good k. In particular, you do not depend so much on how clever the implementation is.
On the other hand, guided may be a good first guess, with a reasonable overhead / load balancing ratio, at least for a clever implementation. Be particularly careful with guided if you know that later iteration times are shorter.
Keep in mind, there is also schedule(auto), which gives complete control to the compiler/runtime, and schedule(runtime), which allows you to select the scheduling policy during runtime.

Once this has been explained, do the sources above support your explanation? Do they contradict at all?

Take the sources, including this anser, with a grain of salt. Neither the chart you posted, nor my timeline picture are scientifically accurate numbers. There is a huge variance in results and there are no error bars, they would probably just be all over the place with these very few data points. Also the chart combines the multiple effects I mentioned without disclosing the Work code.
[From Intel docs]

By default the chunk size is approximately loop_count/number_of_threads.

This contradicts my observation that icc handles my small example much better.
1: Using GCC 6.3.1, Score-P / Vampir for visualization, two alternating work functions for coloring.


text:
Q: Artifactory: how can I obtain a complete dump of all fields for an artifact? I'm interested in the value of one field (Module ID) but there seems to be no way of obtaining this specifically. A complete dump of all field values would also suffice but I haven't succeeded in finding a way to do that either. I've looked at and tried the searches available within the documentation here: https://www.jfrog.com/confluence/display/JFROG/Artifactory+REST+API#ArtifactoryRESTAPI-SEARCHES
If it helps, I'm trying to query an on-premise installation of Artifactory.

A: More fields can be added to the AQL using the "include" element.
For example - to list all artifacts under "libs-release-local" repository, including their module names, run the following query:
items.find(
    {
        "repo":{"$eq":"libs-release-local"}
    }
).include("artifact.module")

Response example:
{
    "results": [
        {
            "repo": "libs-release-local",
            "path": "org/jfrog/test/multi2/2.17.0",
            "name": "multi2-2.17.0.jar",
            "type": "file",
            "size": 1022,
            "created": "2021-09-11T13:51:33.878Z",
            "created_by": "deployer",
            "modified": "2021-09-11T13:51:33.631Z",
            "modified_by": "deployer",
            "updated": "2021-09-11T13:51:33.881Z",
            "artifacts": [
                {
                    "modules": [
                        {
                            "module.name": "org.jfrog.test:multi2:2.17.0"
                        }
                    ]
                }
            ]
        }
    ]
}

You can find all of the required information under AQL documentation.


text:
Q: Converting dates, minutes and seconds to ISOdatetime format in R I have a data frame which is similar to dd where
dd = data.frame(date = as.Date(c("2014-04-29", "2014-04-29","2014-04-29", "2014-04-29", "2014-04-29", "2014-04-29"), format ="%Y-%m-%d"), hh = 1:6, mm = seq(0, 50, 10))

I want to create new variables, call them time1 and time2, where

*

*time1 is time of day, irregardless of the date, e.g.: in row 1  time1 = 01:00 [hh:mm] no entry for seconds

*time2 is date + time1; e.g. for row 1 time2 = 2014-04-29 : 01:00
Any suggestion is appreciated!

A: Check out the lubridate package:
library(lubridate)
dd$time1 <- with(dd, hm(paste(hh, mm, sep=":")))
dd$time2 <- with(dd, ymd(dd$date) + time1)

A: Using base R
dd$time1 <- format(strptime(paste0(dd$hh, ":", dd$mm), "%H:%M"), "%H:%M")
dd$time2 <- format(strptime(paste0(dd$date, ":", dd$hh, ":", dd$mm), "%Y-%m-%d:%H:%M"), "%Y-%m-%d : %H:%M")

Which will result in
dd$time1
## [1] "01:00" "02:10" "03:20" "04:30" "05:40" "06:50"
dd$time2
## [1] "2014-04-29 : 01:00" "2014-04-29 : 02:10" "2014-04-29 : 03:20" "2014-04-29 : 04:30"
##v[5] "2014-04-29 : 05:40" "2014-04-29 : 06:50"

They won't be Date type though (see @MrFlick comment)


text:
Q: Retrain of a neural network I have already trained a NN with training data set [X,Y]. Lets consider this model is called M. Now, I have a new data set [Xnew,Ynew]. I would like to Update my model M with data set [Xnew,Ynew] without retraining it from scratch.
My question is: is it possible to update the model this way or I must retrain this? If it is possible to update, how?

A: Yes, if you're doing e.g. backpropagation. You can take the weights trained on the first data set as the starting point for the training on the second data set, instead of starting with random weights.
Whether this is a sensible thing to do or not is of course highly depends on your data sets and the network topology.


text:
Q: AJAX activities disappear when browsing forward and back This is not a Meta question.
I am trying to technically understand what principle is hidden behind the following behaviour. It's very easy to reproduce:

*

*Vote up/down anything on this page1,

*Click on any other link on this page,

*Come back by pressing the back button.

Your upvote is not there anymore as well as any AJAX activities having appeared on the page.
Why is that? Why is the browser acting like so? How could StackOverflow prevent that?

1 If you are not connected, just wait for someone else's activity on the page (new comment, answer, vote) before moving page.

A: It's the browser's cache that is at play here.
Since you're asked how SO could "prevent" this, it could be done by advising the browser to check for whether the document has changed every time. But SO not doing so, for performance reasons. So the HTML document is seen as "still valid" for a certain amount of time, during which the browser takes it straight from its cache, without making a round-trip to the server.
If you look at the HTTP response headers in your browser's developer tools for the request your browser made for this page, you will see something like this,
Cache-Control:  public, no-cache="Set-Cookie", max-age=60

– so this HTML document is to be considered valid for 60 seconds. If you navigate away from it and back in your browser, or close the tab and reopen it from history, within that 60 seconds, the browser is supposed to take the cached version of it and display it, without checking again with the server whether or not something has changed. And since your vote did not manipulate this original HTML document (only the DOM was updated with your vote), you still get the previous vote count shown.
But if you press [F5] in your browser, the cache will be circumvented – it will request the document from SO again, and then you see your vote, because this time the updated numbers are part of the updated HTML document that SO serves you.
If you want to delve more into HTTP caching, some resources of the top of Google that seem worth a look:
Caching Tutorial for Web Authors and Webmasters
A Beginner's Guide to HTTP Cache Headers

A: You are not "unvoting", you just are not seeing your vote because your browser is caching the ajax request.
If your press F12 on Chrome, click on Settings icon and then "Disable cache (while DevTools is open)", when you press back the browser will resend the request.
To prevent that you must specify on your code that you never want that specific request to be cached.
You may want to check the following post:
Prevent browser caching of jQuery AJAX call result
-
Ps. You must stay with the Console (F12) opened while doing the test.


text:
Q: What is the difference between captures and parameters in a C++ laambda expression? https://en.cppreference.com/w/cpp/algorithm/sort
  std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};

    auto print = [&s](std::string_view const rem) {
        for (auto a : s) {
            std::cout << a << ' ';
        }
        std::cout << ": " << rem << '\n';
    };

    std::sort(s.begin(), s.end());
    print("sorted with the default operator<");

For example, in this code, why is the capture "s" and the parameter "sorted with the default operator<"?
Why is the capture "sorted with the default operator<" and not the parameter "s"?

A: A lambda isn't a function its a class with an operator() that takes your parameters as arguments. So the caputured variables will become members of the class and thus will be reusable and the parameters will be the arguments of the operator.

A: The captured values stay with the lambda object while the function arguments exist only for the call. As with any function you can call the lambda function several times, each with a different argument list to its parameter list. The lambda object, however, is constructed exactly once, at which point the captures are bound to the internal members of the lambda.
If you throw your code into https://cppinsights.io, you get an idea of what the compiler does with your lambda function:
  std::array<int, 10> s = {{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}};

  class __lambda_7_18
  {
    public:
    inline /*constexpr */ void operator()(const std::basic_string_view<char, std::char_traits<char> > rem) const
    {
      {
        std::array<int, 10> & __range1 = s;
        int * __begin1 = __range1.begin();
        int * __end1 = __range1.end();
        for(; __begin1 != __end1; ++__begin1) {
          int a = *__begin1;
          std::operator<<(std::cout.operator<<(a), ' ');
        }

      }
      std::operator<<(std::operator<<(std::operator<<(std::cout, ": "), std::basic_string_view<char, std::char_traits<char> >(rem)), '\n');
    }

    private:
    std::array<int, 10> & s;

    public:
    __lambda_7_18(std::array<int, 10> & _s)
    : s{_s}
    {}

  };

  __lambda_7_18 print = __lambda_7_18{s};
  print.operator()(std::basic_string_view<char, std::char_traits<char> >("sorted with the default operator<"));

As you can see, your print lambda is an object that holds a reference to the captured array: s. When you call it, its operator() member function is invoked with the arguments you pass to it, here an std::string_view with the value "sorted with the default operator<". You'd be free to call it again with a different value.


text:
Q: Grouping items into groups This is a chug-plug formula given in my book :
1.The number of ways in which mn different items can be divided equally int m groups, each containing n objects and the order of the groups is not important,is : $\frac {(mn)!}{(n!)^m} \frac {1}{m!} $
2.The number of ways in which mn different items can be divided equally int m groups, each containing n objects and the order of the groups is important,is : $\frac {(mn)!}{(n!)^m} \frac {1}{m!} * (m!) $
I am having some troubles in understanding the above two formulas and hence making mistakes while solving problems based on the same, so I am very inquisitive to know the proof.

A: *

*Imagine first that both the order of the groups and the order within the groups is important. You have $mn$ items; one way to divide them into $m$ groups of $n$ objects each is to simply list the items. Items 1 through $n$ will go into the first group; items $n+1$ through $2n$ will go into the second group; etc. There are $(mn)!$ ways of listing the items.
But in fact, you don't care about the order in which the groups appear on the list: if you take the same list you have, and now list items $n+1$ through $2n$ first, then, say, times $4n+1$ through $5n$, then items $1$ through $n$, etc., you will still get the same division of objects into the same groupings. So any shuffling of the blocks in your list will yield the same distribution of items into the groups. Each distribution into groups can then be described in $m!$ ways, one for each ordering of the $m$ groups. So you have counted each distribution $m!$ times, and you need to divide $(mn)!$ by $m!$.
You are still not done, though, because you also don't care about the order within each group. Again, say you have a listing: if you take the first $n$ items in the list, and you list them in a different order (say, from last to first) while keeping them in the first $n$ slots, then in the end you will have the same elements separated into the same groups: you don't care who goes into group $1$ first or last, just that they end up in that group. So you have also overcounted by as many ways as there are to list the members of each group in order. In each group, you have $n$ objects, which can be listed in $n!$ different ways. There are $m$ such groups, so each listing of the elements in the groups can be done in $(n!)^m$ ways; so you have also, separately, overcounted the lists by $(n!)^m$, forcing you to also divide by $(n!)^m$. Putting these two overcount factors together gives you the first formula.

*Try to adapt the explanation above to see how to obtain this formula; note that a simpler way of writing it is just as $\frac{(mn)!}{(n!)^m}$, since the two $m!$ will cancel out.

A: Order of the group means that the each of the m groups is ordered as group-1, group-2,.., group-m. Let us understand that better with an example.
Let Arrangement-A be such that Group-1={a1,b1,...,n1}, Group-2={a2,b2,...,n2}...
Let Arrangement-B be such that Group-1={a2,b2,...,n2}, Group-2={a1,b1,...,n1} while all other elements/objects in the remaining groups  remains same as in Arrangement-A.
Now if the order of the groups is not important Arrangement-A is the same as Arrangement-B.
If the order of the groups is important then Arrangement-A is not the same as Arrangement-B.
P.S: I have not provided the proof to the formula as what has been written by Arturo should suffix with this explanation.

A: Let me derive another expression for the following:

The number of ways in which mn different items can be divided equally into m groups, each containing n objects and the order of the groups is not important.

Since the order of items within the group does not matter, there are $C^m_n$ $\cdot$ $C^{m-n}_n$ $\cdot$ ... $\cdot$ $C_n^n$ ways of ordering the n objects into  m groups. This formulation excludes any kind of ordering within the groups. However, this formulation takes into account the ordering between the groups. Hence, it should be divided by m! to account for this. Hence, the number of ways in which mn different items can be divided equally into m groups, each containing n objects and the order of the groups is not important can be expressed as:
$\frac{C^m_n \cdot C^{m-n}_n \cdot ... \cdot C_n^n}{m!}$
Assume that 8 objects have to be divided equally into 4 groups with 2 items each.
Then, it could be calculated as
$\frac{C^8_2 \cdot C^{8-2}_2 \cdot C^{8-4}_2 \cdot C^{8-6}_2}{4!}$


text:
Q: Hibernate criteria for a junction table - how to create? I have simply 3 tables like:
product
.----------
id
name
category
.----------
id
name
product_category
.----------------------
p_id
c_id
I want to get a list of products where the products have category of id=3.
I am confused about how to write a hibernate criteria for this. Any help would be appreciated.
Thanks

A: Criteria c = session.createCriteria(Product.class, "product");
c.createAlias("product.categories", "category");
c.add(Restrictions.eq("category.id", 3));

A: Check this implementation
fluent nhibernate implementation
Fluent nHibernate - How to map a non-key column on a junction table?
nhibernate implementation
http://www.barebonescoder.com/2010/08/nhibernate-many-to-many-relationships/
hope this helps


text:
Q: f is not continuous at any point c of its domain R when the metric d on R is Euclidean Let $f\colon (\mathbb{R},d) \to (\mathbb{R}, |\cdot| )$ be defined as
$$f(x) = \begin{cases}\phantom{-}1, &x ∈ \mathbb{Q} \\-1, &x ∉ \mathbb{Q} \end{cases}$$
I want to prove that $f$ IS NOT continuous at any point $c$ of its domain $\mathbb{R}$ when the metric $d$ on $\mathbb{R}$ is Euclidean .
I want to prove that $f$ IS continuous at all points of its domain when the metric $d$ is the discrete metric.
I know: A function $f$ is called continuous at $x \in X$ if for every $\varepsilon > 0$ there exists $\delta > 0$ such that $ρ(f(y), f(x)) < \varepsilon$ whenever $d(y,x) < \delta$.
AND
I know alternatively: $f\colon X\to Y$ is continuous iff whenever $x_n \to x$ in $X$ we have $f(x_n) \to f(x)$

A: $\Bbb Q$ in $\Bbb R$ and so is $\Bbb R -\Bbb Q$. Hence for every real number $r$ there exist sequences $(a_k) \subset \Bbb Q$ and $(b_k) \subset \Bbb R - \Bbb Q$ such that $a_k \to r$ and $(b_k)\to r$. But $f(a_k)\to 1$  and $f(b_k)\to-1$. Hence f is not continuous. This answers your first question.

A: Hint: Use your last characterization and the sequence
$$x_n = c + \frac{\sqrt{2}}{n} \qquad y_n=c+\frac{1}{n}$$
May be useful separate cases when $c$ is or not rational.

A: Your second characterisation of continuity (called sequentially continuous) is the practical one in this case (and in the case of metric spaces, equivalent to continuity).
1) You want to prove that for a given $c\in \mathbb{R}$ the map $f$ is not continous at $c$. Let's assume that $c\in \mathbb{Q}$, so $f(c)=1$. So you want to find a sequence $x_n$ in $\mathbb{R}$ which converges to $c$ in the euclidean metric such that $f(x_n)=-1$ for all $n$. This would show that $f$ is not continous at $c$. Such a sequence exists, $f(x_n)=-1$ means that $x_n \notin \mathbb{Q}$ . Can you find a sequence in $\mathbb{R} \setminus \mathbb{Q}$ which converges to $c\in \mathbb{Q}$? The case $c\notin \mathbb{Q}$ is analogous.
2) To show that $f$ is continous for $d=\text{discrete}$, you have to understand first, what $x_n \to c$ means in the discrete metric. A sequence $x_n$ converges to $c$ if $d(x_n,c) \to 0$. But the distance in the discrete metric of nonequal points is always $1$. What does that mean for your sequence?


text:
Q: TSQL Degrees of Difference in strings I am trying to compare 2 strings in a sql statement. Some of the string are almost identical and some are very different
For example:
The following 2 addresses are almost identical
22224 143RD AVE
222-24 143RD AVE.

While the next 2 are very different
6969 elmund street
6969 mamerth street

Is there a function to classify the degree of difference?

A: http://support.microsoft.com/kb/100365 lays out DIFFERENCE() and SOUNDEX().  I'm not sure how well these would work in your particular use case.


text:
Q: How to modify tiff creation date in .Net I am writing a pdf comparison utility. After some investigation it seems like the best way to do this is to convert to tiff and compare from there.
I managed to do this with Ghostscript but am getting a difference in the embedded creation date metadata.

How do I use .Net to modify this?

A: After more investigation, it seems Microsoft does provide a TIFF library with multi-image support. It's in System.Windows.Media.Imaging. To get this namespace reference PresentationCore.
To access the TIFF metadata use this site as a reference: http://www.awaresystems.be/imaging/tiff/tifftags/baseline.html
This code accesses the date field after the GhostScript name you were interested in:
    FileInfo fi = new FileInfo(@"C:\Users\Chris\Downloads\PdfVerificationTests.can_use_image_approval_mode.approved.tiff");
    FileStream stream = fi.Open(FileMode.Open, FileAccess.ReadWrite,FileShare.None);
    TiffBitmapDecoder decoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    BitmapMetadata bmd = (BitmapMetadata) decoder.Frames[0].Metadata;
    string thedateval = (string) bmd.GetQuery("/ifd/{ushort=306}");
    BitmapMetadata bmd2 = bmd.Clone();
    bmd2.SetQuery("/ifd/{ushort=306}", "2013:05:30 20:07:52");

This code does not write out a modified TIFF, but is all the info you need to do so. Hope this helps as I feel I'm beating a dead horse.
This code will strip all the attributes from a multipage TIFF and leave the image content intact:
    FileInfo fi = new FileInfo(@"C:\Users\Chris\Downloads\PdfVerificationTests.can_use_image_approval_mode.approved.tiff");
    FileStream stream = fi.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    TiffBitmapDecoder decoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
    FileStream stream2 = new FileStream("empty.tif", FileMode.Create);
    TiffBitmapEncoder encoder = new TiffBitmapEncoder();
    for (int i = 0; i < decoder.Frames.Count(); i++)
    {
        BitmapSource source = decoder.Frames[i];
        int stride = source.PixelWidth * (source.Format.BitsPerPixel / 8);
        byte[] data = new byte[stride * source.PixelHeight];
        source.CopyPixels(data, stride, 0);
        CachedBitmap theSource = (CachedBitmap)BitmapSource.Create(source.PixelWidth, source.PixelHeight, source.DpiX, source.DpiY, source.Format, source.Palette, data, stride);
        encoder.Frames.Add(BitmapFrame.Create(theSource));
    }
    try
    {
        encoder.Save(stream2);
        stream2.Close();
        stream.Close();
    }
    catch
    {
    }

A: You can use LibTiff.NET. It is open source. Using this library, you can use the SetField method to modify any one of the many tags in the Tiff file, including the TiffTag.DATETIME flag.

A: If the date stamps are fixed size, a fun workaround for this type of problem is to write a FileStream which simply detects and blanks out such date stamps. In fact I've done this before for PDF comparison, on a project I worked on in school. The checksum comparison worked fine with just that, without any conversion to tiff, though in our specific case we were sure all compared PDFs were generated by the same system, so that simplified things a bit.
The basic method is to make a subclass of FileStream with overridden ReadByte and Read functions, which contains the length and expected format of the date stamps. Whenever a read is performed the following happens:

*

*The code reads an extra piece, the size of the datestamp length minus 1 byte, both before and behind the requested data.

*Inside that block, a search and replace is performed to clear any found date stamps.

*Finally, the original requested piece is returned.

The source code I wrote for the project back in the day is here.

A: It seams that this ghostscript behavior could be supressed.

-dTIFFDateTime=false

https://www.ghostscript.com/doc/9.22/Devices.htm
... but for this situation I would recommend some diffpdf tools (http://soft.rubypdf.com/software/diffpdf)
D


text:
Q: Пункты меню не отображаются в строке меню Apple. У меня есть приложение на Java с главным меню. Но при запуске на Маке эти пункты меню не отображаются в главной строке меню Apple вверху экрана, а располагаются в окне приложения стандартно, т.е. выглядит как в Windows. В чем может быть проблема? Меню создаю стандартным способом:
JMenuBar mainMenu = new JMenuBar();
mainMenu.add(new JMenu("Menu 1"));
...
frame.setJMenuBar(mainMenu);

A: Если я не ошибаюсь, то надо либо использовать какую-нибудь библиотеку, которая использует нативные контролы (такая, как SWT), либо использовать аээпловское апи для этого меню (как делает, например, нетбинс)
Прочтите также вот это: Bringing your Java Application to Mac OS X. В этой статье есть речь и про меню.
PS: я всё-таки не совсем прав. Однако, судя по документу, достаточно пропихнуть аргументы при запуске:

-Dcom.apple.macos.useScreenMenuBar=true -Xdock:name="window name on dock panel"


text:
Q: Access current tab url in background.js chrome extension Would like to access the current tab url in background.js
Had already used following code in background.js
 window.chrome.tabs.query({ "active": true, "windowId": window.chrome.windows.WINDOW_ID_CURRENT },
    (tabs) => {
        console.log("Tab Url ", tabs);
        if (Array.isArray(tabs) && tabs.length > 0 && tabs[0]["url"]) {
            console.log("Tab Url ", tabs[0]["url"]);
        }
    }
);

chrome.tabs.getAllInWindow(undefined, function (tabs) {
    for (var i = 0, tab; tab = tabs[i]; i++) {
        console.log(tab);
        if (tab.url) {
            console.log(tab.url)
        }
    }
});

chrome.tabs.getCurrent(function (tab) {
    console.log(tab.url);
});

chrome.tabs.query({ 'active': true, 'lastFocusedWindow': true, 'currentWindow': true }, function (tabs) {
    var url = tabs[0].url;
    console.log(url);
    alert(url)
})

With and without parent function
window.chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab){...code})

manifest.json
"background": {
  "scripts": [
    "background.js"
  ],
 "persistent": true
},
"permissions": [
  "identity",
  "activeTab",
  "tabs"
],

For all the above results, I am receiving undefined for the current URL.
Any guidance is appreciated.

A: Rather than doing window.chrome.tab.query you can just do chrome.tabs.query. Also in the updated version of the chrome API, you can get the current tab url by passing currentWindow and active as true.
So, the request to get the current tab becomes :

const currentTab = chrome.tabs.query({currentWindow: true, active: true}, function(){});
console.log(currentTab.url);


text:
Q: Inject Dependencies into Validation Attribute using ASP.NET Core's WebAPI I'm building a Custom Validation Attribute in ASP.NET Core WebAPI. I need to access IDataProtector in my validator and another service I'm using to access the database. I've searched and wasn't ab;e to find any documentation for this. ActionFilters have the option of using ServiceFilter but there doesn't seem to be any option for Validation Attribute. Any ideas?

A: Use the GetService() method of the ValidationContext to get your database.
i.e.
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
  MyDbContext db = (MyDbContext) validationContext.GetService(typeof(MyDbContext));
  //...
}

A: You can override IsValid method and use validationContext to resolve dependency:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var service = (IExternalService) validationContext.GetService(typeof(IExternalService));
    // use service
}

A: We had a similar requirement where additional data was needed to be passed to an attribute to provide enough context for it to perform the validation.
We came up with a way to build up a context object which could be passed to attributes. I blogged about it here.
We are using the async api to perform data access which presented some additional challenges.

A: Because validation attributes are typically defined on properties, they can't receive a reference via the constructor.  At best if you did really deep into model binding, there may be something to customize to allow property injection, but most practically I just get a reference to the dependency resolver in the Validate method, and call the appropriate method.


text:
Q: How to access Gradle `project` from `buildSrc`? I have the following in buildSrc:
class MyClass {
    def doSomething() {
        final familyMembers = project.configurations['compile'].allDependencies.collect { dep ->
            dep.name
        }
    }

but when I try to use it in build.gradle:
task 'do-something' << {
    final myObject = new MyClass()
    myObject.doSomething()
}

the following error is emitted:
* What went wrong:
Execution failed for task ':my-project:do-something'.
> No such property: project for class: MyClass

How do I get project to be visible within MyClass?

A: You'll have to pass project as a parameter to MyClass.
For example, declare a constructor and a member variable:
    class MyClass {
        private Project project

        MyClass(Project project) {
          this.project = project
        }

        def doSomething() {
            final familyMembers = project.configurations['compile'].allDependencies.collect { dep ->
                dep.name
            }
        }

and then use it from your project as such:
    task 'do-something' << {
        final myObject = new MyClass(project)
        myObject.doSomething()
    }


text:
Q: AngularJs:-how to dynamically push images into div and upload it to server in AngularJs I am trying to implement a Crm kind of application..I have implemented a small  feature in which I can select a div from various options. I have given a button to push the image in the div and also ng-style to set the properties.
The problem is I have used ng-model to push the image in the div..Now because of this when I am trying to push images into a new div I am getting the same image over and over again.Can anyone please give the solution to this
The issue is how do I control the image and the parameters which are given by the user and simultaneously display the same thing in the UI.
The below is my code.. cms.html:-

Display Picture 1:
            <input type="file" ngf-select="" ng-model="picFile" name="file" ngf-accept="'image/*'" required="">
            *required

Display Picture 2:
            <input type="file" ngf-select="" ng-model="picFile1"  name="file" ngf-accept="'image/*'" required="">
            *required

Display Picture 3:
            <input type="file" ngf-select="" ng-model="picFile2"  name="file" ngf-accept="'image/*'" required="">
            *required

{{myText}}

{{myText1}}

          <ng-include src="layout" class></ng-include>

the below is my javascript code:-
$scope.items = ['grid-12', 'grid-6-6', 'grid-4-8', 'grid-8-4', 'grid-4-4-4'];
$scope.selectedLayouts = [];

$scope.open = function() {

    var modalInstance = $uibModal.open({
    animation: true,
    templateUrl: 'layoutTemplateModal.html',
    controller: $scope.LayoutModalCtrl,
    size: 'lg',
    resolve: {
      items: function() {
        return $scope.items;
      }
    }
  });

  modalInstance.result.then(function(selectedItem) {
    $scope.selectedLayouts.push(selectedItem);

  }, function() {
    $log.info('Modal dismissed at: ' + new Date());
  });

};

Please help me out..
Thanks

A: Although there isn't enough code shown to narrow down where selectedItem comes from in your modal controller , the following should help.
Use angular.copy() to prevent pushing the same object reference into array
Try changing:
$scope.selectedLayouts.push(selectedItem);

To:
$scope.selectedLayouts.push(angular.copy(selectedItem));


text:
Q: Change content of a div using JavaScript How to dynamically change content of a div using JavaScript?

A: document.getElementById("divId").innerHTML = "new content!"
I would recommend using a framework like jQuery though, because chances are you will be doing more things like this later.

A: Its worth noting that you can also use innerHTML to include other markup. Also if the DIV des not have an ID you can try using getElementsByTagName.
Example, to get the first DIV in the document:
document.getElementsByTagName("div")[0].innerHTML = "
This is a new paragraph
";

This allows you to loop through multiple DIVs in the document and check other conditions.
And like they said above, if the DIV has an ID that you know will always be there, then thats better to use:
document.getElementById("theID").innerHTML = "
This is a new paragraph
";

Check out Prototype (links below) (or jQuery) in handling this as they make life easier, especially when you get into CSS selectors:

*

*http://api.prototypejs.org/dom/dollar.html

*http://api.prototypejs.org/dom/dollardollar.html

*http://api.prototypejs.org/dom/element.html#select-class_method

A: This should do it:

Div you want to change

And in JavaScript:
document.getElementById('foo').innerHTML = 'Your content';

A: $(document).ready(function(){

$('#btn').click(function(){

    $('#div_content').load('html.page');

 });
});


text:
Q: gcloud command not found in google cloud Functions Python I want to user gcloud command in cloud Functions source
main.py
import os
command = 'gcloud --project {}~~'

os.system(command)

but erorr
sh: 1: gcloud: not found

A: As @puteri said You may need to use the libraries of the product you wish to interact with.
So, Can you install this Python Client for Cloud Functions and also refer to this multiple Python Cloud Client Libraries . Post installing this python client that may help in resolving your issue.
Also, gcloud command not found error occurs if your installation is unsuccessful due to the find command not being recognized find this SO . You can Try another alternate way to  resolve this issue by installing the cloud SDK


text:
Q: How can I read SD card on ubuntu? I read various topics here, but wasn't able to find solution for my problem.
I have a sdcard reader on my dell v131 laptop with ubuntu 15.10 installed. I insert my sdcard to reader and cannot find it in media folder.
Output of dmesg |tail:
[ 2598.842091] usb 4-1.6: New USB device found, idVendor=0bda, idProduct=0138
[ 2598.842102] usb 4-1.6: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 2598.842108] usb 4-1.6: Product: USB2.0-CRW
[ 2598.842112] usb 4-1.6: Manufacturer: Generic
[ 2598.842117] usb 4-1.6: SerialNumber: 20090516388200000
[ 2598.848716] ums-realtek 4-1.6:1.0: USB Mass Storage device detected
[ 2598.865053] scsi host14: usb-storage 4-1.6:1.0
[ 2599.869001] scsi 14:0:0:0: Direct-Access     Generic- Multi-Card       1.00 PQ: 0 ANSI: 0 CCS
[ 2599.869776] sd 14:0:0:0: Attached scsi generic sg1 type 0
[ 2606.258161] sd 14:0:0:0: [sdb] Attached SCSI removable disk

Sdcard in disks:

The /media folder is empty.
Output of cat /proc/partitions | grep sdb is empty
How can I acces my sdcard?
UPD: It seems that my sdcard is dead since format option is grayed out in disks utility. I don't have a second card in touch to verify this. Anyway thank you all for support.

A: check your partitions inside
# cat /proc/partitions

If you have there something like
# cat /proc/partitions | grep sdb
   8        0  234431064 sdb
   8        1     524288 sdb1

You can try to mount sdb1
# sudo mkdir /media/sdb1
# sudo mount /dev/sdb1 /media/sdb1

A: Simplest way:
sudo mkdir /media/sd
sudo mount /dev/sdb /media/sd

Your SD card's contents will now be under /media/sd/.
If your SD card has  non-readable filesystem (aka one that Ubuntu doesn't support) you'll have to format it (and lose all your data before you can use it).


text:
Q: Php - While [data] loop, $Post returning only first value I have this code, who retrieve AD account, mail, enabled from database.
Display is ok, and i'm adding an update button at each line (UpdateAccount) who permit updating account informations.
But when i'm submitting an update $Post values are always values from the first account (not the account i've selected).
Exemple :
https://imgur.com/a/GUCOd
Problem :
When i want to update the second account, $post send me data from the first account.
When i want to update the third account, $post send me data from the first account.
I think i need to pass a "$post ID" somewhere who contain the data i've selected, if you have any solution ...
Code :
<?php
$data = '';

# Retrieving account in database

$sql = "SELECT ".USERAD_ID.",".USERAD_ENABLED.",".USERAD_ACCOUNT.",".USERAD_EMAIL." FROM ".USERAD_TABLE."";
$mydb = new DB();
$result = $mydb->runQuery($sql);

# Template Column

echo "

ID

Compte AD

Adresse Mail

Etat

";

# While Account in $result, display data

while($data = mysqli_fetch_assoc($result)) {

$id     =   $data[USERAD_ID];
$account    =   $data[USERAD_ACCOUNT];
$email      =   $data[USERAD_EMAIL];
$enabled    =   $data[USERAD_ENABLED];

echo "

<input type='textsmall' required name='id' id='id' value='".$id."' '>

<input type='textsmall' required name='account' id='account' value='".$account."' '>

<input type='textsmall' required name='email' id='email' value='".$email."' '>

<input type='textsmall' required name='enabled' id='enabled' value='".$enabled."' '>

        <form id='updatead' role='form' method='post'>

                    <input type='hidden' name='id' value='".$id."'>
                    <input type='hidden' name='account' value='".$account."'>
                    <input type='hidden' name='email' value='".$email."'>
                    <input type='hidden' name='enabled' value='".$enabled."'>
        </form>

        <INPUT type='submit' class='form-updatead' value='updatead' name='submit'></INPUT>

";
}

?>

A: If you have multiple forms on a single page then your submit button just will post the first one by default. Considering removing the INPUT and use a button or div. Like this:
echo "

<input type='textsmall' required name='id' id='id' value='".$id."' '>

<input type='textsmall' required name='account' id='account' value='".$account."' '>

<input type='textsmall' required name='email' id='email' value='".$email."' '>

<input type='textsmall' required name='enabled' id='enabled' value='".$enabled."' '>

    <form id='".$id."' role='form' method='post' action='/doSomething.php'>

                <input type='hidden' name='id' value='".$id."'>
                <input type='hidden' name='account' value='".$account."'>
                <input type='hidden' name='email' value='".$email."'>
                <input type='hidden' name='enabled' value='".$enabled."'>
    </form>

    <button onclick='document.getElementById('".$id."').submit()'>Submit</button>

";

Note: I also added an "action='/doSomething.php'".

A: Thanks, it's working perfectly.
Here is the final code working :
<?php

while($data = mysqli_fetch_assoc($result)) {

$id         =   $data[USERAD_ID];
$enabled    =   $data[USERAD_ENABLED];
$account    =   $data[USERAD_ACCOUNT];
$email      =   $data[USERAD_EMAIL];

echo "

        <form id='".$id."' role='form' method='post' action='./admin/permissionsform.php?page=updatead'>
            <input type='hidden' name='id' value='".$id."'>

<input type='textsmall' required name='account' id='account' value='".$account."' style='width:75%'>

<input type='textsmall' required name='email' id='email' value='".$email."' style='width:75%'>

<input type='textsmall' required name='enabled' id='enabled' value='".$enabled."' style='width:75%'>

        </form>

        <button class='buttoneditsrv' onclick='document.getElementById(".$id.").submit()';window.location='./?view=list&search='>Mise &agrave jour</button>

";
}
?>


text:
Q: how to avoid while loop and return in scala I see in scala it is a bad practice to use both while and return. I have to click on the next page link if it exists. How can I do it without while and return?
def check = {
  do {
    if (findElements(locator).exists(_.getText.contains(input)))
      return true
  } while (nextPageLocatorInPageExists(nextPageLocator))
  false
}

A: Here's a straightforward recursive solution:
def check = {
  if (findElements(locator).exists(_.getText.contains(input)))
    true
  else if (! nextPageLocatorInPageExists(nextPageLocator))
    false
  else
    check
}

It can be written in a terser way by using || and &&, but then it wouldn't be tail recursive, and that's pretty much mandatory in a case like this.

A: From your code, I'm guessing nextPageLocatorInPageExists(nextPageLocator) mutatates locator, and that's what drives your while loop.
If that's the case, here are two options:
a do-while loop without return: the closest to what you wrote:
def check = {
  var found = false
  do {
    found = findElements(locator).exists(_.getText.contains(input))
  } while (!found && nextPageLocatorInPageExists(nextPageLocator))
  found
}

a recursive solution
def check: Boolean = findElements(locator).exists(_.getText.contains(input)) ||
                     (nextPageLocatorInPageExists(nextPageLocator) && check)


text:
Q: How To Share object state across all Azure Function Instances We have a C# Azure Function App (consumption plan) which scales dynamically i.e new instances are added depending on the load, now we have an object which needs to be used across all instances of this Azure Function, as the object is complex (has delegates) I cannot serialize to put on an external cache so that all instances can access it from there, please suggest the best way to handle this scenario.

A: Azure Function instances are running on different servers, they do not share the same memory, so there is no way for all of them to access a single .NET object without remote calls (and thus serialization).

A: There's something fundamentally contradictory in your question: you can't have both a) a function that scales to many machines; b) all instances sharing in-memory objects as if they were running on a single machine.
It goes the other way too: serverless means that if nobody is using your function, all infrastructure can be shut down (hence saving you money) - but that implicitly means you'd lose your in-memory state and need to be able to serialize it.
Minimize the shared state, make it serializable (there are patterns for dealing with things like delegates [1]),  and use external storage (Azure Storage, or a cache like Redis).
[1] For delegates, one trick is to maintain a dictionary of handles to delegates, and then serialize the handle. Similarly, for polymorphism, you might serialize the type name.