text:
Q: "Cannot assign to the result of this expression" error arising from a variable (var) I have defined the following subclass whose main property is linked to an enumeration:
let NumberOfColors: UInt32 = 6

enum SphereColor: Int, Printable {
case Red = 0, Yellow, Blue, Green, Purple, White

var sphereName: String {
    switch self {
    case .Red:
        return "red"
    case .Yellow:
        return "yellow"
    case .Blue:
        return "blue"
    case .Green:
        return "green"
    case .Purple:
        return "purple"
    case .White:
        return "white"
    }
}

var description: String {
    return self.sphereName
}

static func random() -> SphereColor {
    return SphereColor(rawValue: Int(arc4random_uniform(NumberOfColors - 1)))!
    }
}

class Sphere: SCNSphere {
var color : SphereColor

init(radius: CGFloat, color: SphereColor) {
    self.color = color
    super.init()
    switch color.rawValue as Int {
    case 0:
        self.firstMaterial?.diffuse.contents = UIColor.redColor()
    case 1:
        self.firstMaterial?.diffuse.contents = UIColor.yellowColor()
    case 2:
        self.firstMaterial?.diffuse.contents = UIColor.blueColor()
    case 3:
        self.firstMaterial?.diffuse.contents = UIColor.greenColor()
    case 4:
        self.firstMaterial?.diffuse.contents = UIColor.purpleColor()
    case 5:
        self.firstMaterial?.diffuse.contents = UIColor.whiteColor()
    default:
        break
    }
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
    }
}

Instantiating it using
let sphere = Sphere(radius: radius, color: SphereColor.random())

let sphereNode = SCNNode(geometry: sphere)

works fine, but when I select one of the nodes and try to change its color property with
// node selection...
var geom = node.geometry! as! Sphere
geom.color.rawValue = 5

I get the "Cannot assign to the result of this expression" error, but I haven't declared the color property as a constant and don't understand why this is happening. I assume I have made some fundamental mistake in the code relative to the Sphere class, any ideas on what this could be?
EDIT: using
geom.color = SphereColor(rawValue: 5)!

as Martin R said, allows me to build and run my code but the color of the sphere doesn't change, which makes me think there's still something wrong with my subclass declaration.

A: rawValue is a read-only property and you cannot assign a new value
to it. You have to create a SphereColor from
the raw value and assign it to the color property:
geom.color = SphereColor(rawValue: 5)!

or if there is any chance that the raw value might be out-of-range
and no matching color exists:
if let color = SphereColor(rawValue: 5) {
    geom.color = color
}

A: Props to @MartinR for fixing the first problem, but my response for the rest of it is too big for a comment.
As noted, rawValue is a read-only property of an enum. Enums are value types, so you don't change the value of an "instance" of the enum, you create a new value. (Think of enums as fancy numbers. You don't change 7 itself into another number, you change a variable holding the value 7 to hold another value.) To create an enum value from the corresponding raw type, use the init(rawValue:) initializer.
Your second problem is that you're updating the model (the part that tells you what color you think your ball is, in a conceptual / semantic way) but you're setting the visual representation of that model (the SceneKit stuff you can see) only when you create a Sphere, not when you set its color property. If you want to keep model and view in sync, you need to make that happen.
You already have code for translating a Color into a SceneKit material color, in your initializer. Factor that out so you can also call it from someplace else, and then you can use it to update your view when the model changes — say, with a property observer.
Here's that, plus some other improvements:
class Sphere: SCNSphere {

    func setMaterialColor(sphereColor: SphereColor) {
        let color: UIColor
        // Switch on the enum, not the int.
        // That way the compiler can check exhaustiveness,
        // and you don't need a dead default case.
        switch sphereColor {
            case .Red:
                // Use a temporary for the color choice so
                // you're only setting the material property once.
                color = UIColor.redColor()
            case .Yellow:
                color = UIColor.yellowColor()
            case .Blue:
                color = UIColor.blueColor()
            case .Green:
                color = UIColor.greenColor()
            case .Purple:
                color = UIColor.purpleColor()
            case .White:
                color = UIColor.whiteColor()
        }
        // Force-unwrap firstMaterial -- we "know" it should be non-nil,
        // so it's better to find out the hard way if something weird has happened.
        // (Either that or test the optional so you can manage failure specifically.)
        self.firstMaterial!.diffuse.contents = color
    }

    var color : SphereColor {
        didSet {
            self.setMaterialColor(color)
        }
    }

    init(radius: CGFloat, color: SphereColor) {
        self.color = color
        super.init()
        self.setMaterialColor(color)
    }

    required init(coder aDecoder: NSCoder) { /* ... */ }
}


text:
Q: Way to communicate between two sibling components using angular 7 without using a common service for both Here i want to communicate between two components of a same parent.Basically,i want to pass the data from one component to another.
FirstComponent.ts
constructor(
    private service: service1,
    private serve: service2,
) {}

ngOnInit() {
    this.service.getUser().subscribe((data) => {
        this.serve.setAccount("1", "apple");
        this.serve.setEnvironment("Happy");
    })
}

SecondComponent.ts
constructor(private usingService : service2) { }

 ngOnInit() {
 this.Account = this.serve.getAccount();
 this.environmentDetails = this.serve.getEnvironment();

 }

I need to retrieve data from firstComponent to second.here first component is loading after the second component.soo,the data set by first component comes later by in picture.
Tried using subject of rxjs.but,How can we use subject in firstComponent.ts of this example?
How i can communicate between these two components being they are siblings of each other?please help

A: You could use @Input() @Output() decorators with an EventEmitter.  The parent component will set data on the children via a binding.  The children will emit new data back to the parent and reset the data that the children receive.
parent.component.ts
@Component({
  selector: 'app-parent',
  template: `
              <app-first-component
                  [data]="data" (onData)="updateData($event)"></app-first-component>
              <app-second-component
                  [data]="data" (onData)="updateData($event)"></app-second-component>
            `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  public data: any;

  constructor() {}

  updateData(event) {
    this.data = event;
  }

}

first.component.ts
@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements {

  @Input()
  public data: any

  @Output()
  public onData: EventEmitter<any> = new EventEmitter<any>();

  constructor() { }

  updateData(data) {
    //send data back to parent
    //data could be coming from a service/async http request as well.
    this.onData.emit(data)
  }

}

second.component.ts
@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements {

  @Input()
  public data: any

  @Output()
  public onData: EventEmitter<any> = new EventEmitter<any>();

  constructor() { }

  updateData(data) {
    //send data back to parent
    //data could be coming from a service/async http request as well.
    this.onData.emit(data)
  }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send parameter with accentuation c# I have an page and in my Send event, I need pass as a parameter an value "Name".
But this name have accentuation and, in example for name "Raúl Lozada" sends "Raúl Lozada" to my procedure parameter.
How I can correct it?
In my HTML page, it loads correctly!
<asp:BoundField DataField="User" HeaderText="User" />

SqlParameter myParam4 = oCommand.Parameters.Add("@User", SqlDbType.NChar);
            myParam4.Value = row.Cells[0].Text;

A: You need to HTML unescape the string, before sending to the DB:
Use HttpUtility.HtmlDecode:
myParam4.Value = HttpUtility.HtmlDecode(row.Cells[0].Text);


text:
Q: AWS Amplify: How to resend code when Auth 'signIn' API returns 'UserNotConfirmedException' I have an unconfirmed aws cognito user which did not verify his email during registration process. When he tries to login with following code:
Auth.signIn({
    username:email,
    password:password,
})

the API returns

'UserNotConfirmedException'

Now at this point the user is unauthenticated, there is no current session or current user. How will this user be able to verify himself and get himself logged in?

'verifyCurrentUserAttribute' and 'resendSignUp' APIs do not work for unauthenticated user.
Please help.

A: Late response but just saw this: The Auth.resendSignUp(<username>) does not need an authenticated user and is suited for this purpose. It accepts a username parameter as a string and when called will send a new code to the method configured in Cognito.

A: The right API endpoint for confirming a signup is confirmsignup
see : https://aws-amplify.github.io/amplify-js/api/classes/authclass.html#confirmsignup
This entpoint requires an email address and the code. The user can thereby confirm his signup later with the code he has received.


text:
Q: Azure Virtual Machine can't serve websites I am unable to get an Azure VM running Windows Server 2012 to serve up the IIS default website from it's public static IP.

*

*Created a VM running Win Server 2012 R2 and installed web server role.

*Browse to localhost and can see the default website is working

*In Azure, configured the VM to have a Public Static IP address and added DNS name to azure which is publicly resolving to the static IP.

*In Azure, configured a Security Group for the VM network interface and added the following rules:
allow-http    source: any    source port: 80    dest: any    dest port: 80    service: tcp/80    action: allow
allow-https    source: any    source port: 80    dest: any    dest port: 80    service: tcp/443    action: allow

*In Windows Firewall settings, made sure the rules to allow HTTP and HTTPS traffic are enabled. (I have also tried disabling the firewall entirely).

*In IIS make sure the default website is bound to any IP address.
When I try to connect to the VM static IP address, e.g.: http://MY.PUBLIC.STATIC.IP, I cant connect at all. I can't PING the server either.
Any ideas on what I am doing wrong?

A: You are limiting incoming connection to port 80 only. Client browsers can use a port number ranging from 1024 and 65536 for their outgoing connection.
You need to change your security group settings to allow incoming connections from Any port:
allow-http    source: any    source port: any    dest: any    dest port: 80    service: tcp/80    action: allow
allow-https    source: any    source port: any    dest: any    dest port: 80    service: tcp/443    action: allow

A: Instead of specifying "any" against 'destination port' in both of your rules, you need to specify port "80" and "443" as destination ports.
With that, when you put http://MY.PUBLIC.STATIC.IP your traffic will reach port 80; and when you put https://MY.PUBLIC.STATIC.IP your traffic will reach 443.
From this Microsoft's link, check the sub-topic 'NSG for FrontEnd subnet'.


text:
Q: Как отсортировать массив? Допустим был массив
Данные:
['1','2','3','4']

Ключи порядка:
[1,2,3,4]

Поместим '3' на 1 место.
Данные:
['3','1','2','4']

Старые ключи порядка:
[3,1,2,4]

Как можно отсортировать этот массив средствами javascript
['1','2','3','4']

Зная только ключи порядка и имея сам массив?
 var myArr =     ['1','2','3','4'];
 var orderList =  [3,1,2,4];

A:

var myArr =     ['1','2','3','4'];
var orderList =  [3,1,2,4];
var ans=[];

orderList.forEach(function(child) {
 ans.push(myArr[child-1])
});
console.log(ans);

ans - отсортированный массив


text:
Q: upload image using angular and spring boot into postgres I'm trying to upload image into database sql, at first i add column into database called photo and the data type is varchar(100) then in post contrller i do this  :
@PostMapping("/save")
public ResponseEntity<Invoice> addInvoice(@RequestBody InvoiceDTO invoice , @RequestParam("image") MultipartFile multipartFile) throws IOException {

    String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
    invoice.setPhoto(fileName);
    Invoice savedInvoice = invoiceService.saveInvoice(invoice);
    String uploadDir = "user-photos/" + savedInvoice.getId();
    FileUpload.saveFile(uploadDir, fileName, multipartFile);
    LOGGER.info(" invoice saved  " + invoice.getSerialNumber() + "and id : " + invoice.getId());
    return new ResponseEntity<>(savedInvoice, HttpStatus.CREATED);

}

and i create FileUpload class to and this is what it's contains :
public class FileUpload
{
    public static void saveFile(String uploadDir, String fileName,
                                                    MultipartFile multipartFile) throws IOException {
    Path uploadPath = Paths.get(uploadDir);

    if (!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
    }

    try (InputStream inputStream = multipartFile.getInputStream()) {
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ioe) {
        throw new IOException("Could not save image file: " + fileName, ioe);
    }
}
}

and in angular form i do this :

  <form class="form" [formGroup]="addstudentform" enctype="multipart/form-data" >

 Add new invoice

    <input formControlName="serialNumber" type="number" placeholder=" serialNumber ">

    <input formControlName="status" type="text" placeholder=" status">

    <input formControlName="customerSerialNumber" type="text" placeholder="customer serial number">

    <input formControlName="employeeSerialNumber" type="text" placeholder="employee serial number">

    <input type="file" name="image" accept="image/png, image/jpeg" />

    <button  (click)="onSave()" type="submit" class="main-btn"> Save</button>

  </form>

and this is my typescript :
export class AddInvoiceComponent implements OnInit {

  addstudentform: FormGroup = this._formbuilder.group({
    serialNumber: ['', Validators.required],
    status: ['', Validators.required],
    customerSerialNumber: ['', Validators.required],
    employeeSerialNumber: ['', Validators.required],

});

constructor(private _formbuilder: FormBuilder,
    private _http: HttpClient
) { }

ngOnInit(): void { }

onSave(): void {

    let serialNumber = this.addstudentform.get('serialNumber')?.value;
    let status = this.addstudentform.get('status')?.value;
    let customerSerialNumber =this.addstudentform.get('customerSerialNumber')?.value;
    let employeeSerialNumber = this.addstudentform.get('employeeSerialNumber')?.value;

    let body = {
      serialNumber: serialNumber,
      status: status,
      customerSerialNumber: customerSerialNumber,
      employeeSerialNumber: employeeSerialNumber
    }
    console.warn(body);

    this._http.post("http://localhost:8085/invoice/save", body).subscribe()

}
}

and all of this not working and return error:

error: "Internal Server Error" message: "Current request is not a
multipart request"

help please..

A: The 'save' endpoint expects a form to be posted in the request and in your Angular component you send JSON data. What you have to do is update your Angular component and send a multipart request by using  FormData:
var formData:any = new FormData();
formData.append("serialNumber",this.addstudentform.get('serialNumber')?.value);
formData.append("status",this.addstudentform.get('status')?.value);
formData.append("customerSerialNumber",this.addstudentform.get('customerSerialNumber')?.value);
formData.append("employeeSerialNumber",this.addstudentform.get('employeeSerialNumber')?.value);
formData.append("photo",this.addstudentform.get('photo')?.value);
this._http.post("http://localhost:8085/invoice/save", formData).subscribe()

and in your HTML you have to change:
<input formControlName="photo" type="file" name="image" accept="image/png, image/jpeg" />

A: using multipart request as described in the answer you'll also need to modify the controller method according to the form params.
addInvoice(@RequestParam(name='serialNumber') String serialNumber,
@RequestParam(name='status') String status,
/** add other params... */
 @RequestPart(name='photo') MultipartFile photo) throws IOException {
}

https://www.baeldung.com/sprint-boot-multipart-requests


text:
Q: Expiration of HashMap in Redis python? I want to store the following hash map in redis:
"data": {
       "name": "XYZ",
       "age": 22,
       "address": "a-z"
}

I want this whole hash map (with the given key) to expire in time, let's say 72 hours.
How do I use ttl/expire function in python?

A: Thanks,
Following is what I want to do, I guess it is right:
def put_data(name=hash_name, key=hash_key, value=hash_data):
    import redis
    r = Redis.get_connection()
    ttl = datetime.today() + timedelta(hours=72)
    r.hset(name=name, key=hash_key, value=hash_data)
    r.expire(name=hash_name, time=ttl)

A: This is how:
redis_client.expire(your_key, time_in_seconds)

See the documentation.

A: Assuming you only want to store these values and not the top level dictionary you have shown in the post you would use hmset then you would use expire to set the ttl or expireat to set the expiration time on the hashmap


text:
Q: Combinatorial number theory, what is $\lim_{n \to \infty} {\ln f(n)\over \ln n}$? Let $\textbf{Z}_n$ be the set $\{0, 1, \ldots, n - 1\}$ with addition mod $n$. Consider subsets $S_n$ of $\textbf{Z}_n$ such that $(S_n + k) \cap S_n$ is nonempty for every $k$ in $\textbf{Z}_n$. Let $f(n)$ denote the minimal number of elements in such a subset. What is$$\lim_{n \to \infty} {\ln f(n) \over \ln n} \text{ ?}$$

A: The limit is $1/2$.
First we rephrase the condition that $(S_n + k) \cap S_n$ is nonempty for all $k$, as follows. For every $k$ in $\textbf{Z}_n$, there are elements $x$ and $y$ in $S_n$ such that $x - y \equiv k$ (mod $n$). We call $S_n$ a difference set modulo $n$ if this condition is satisfied.
For a difference set $S_n$ with $m$ elements, there are at most $m^2$ possible differences. This shows that $(f(n))^2 \ge n$, and therefore$${{\log f(n)}\over{\log n}} \ge {1\over2}.$$On the other hand, let$$T_n = \{1, 2, 3, \ldots, \lfloor\sqrt{n}\rfloor, 2\lfloor\sqrt{n}\rfloor, 3\lfloor\sqrt{n}\rfloor, \ldots, \lfloor\sqrt{n}\rfloor^2\}.$$We claim that for $n \ge 16$, $T_n$ is a difference set modulo $n$. Note that any integer from $0$ to $\lfloor\sqrt{n}\rfloor^2 - 1$, inclusive, is a difference of two elements of $T_n$. When $n \ge 16$, we have$$\lfloor\sqrt{n}\rfloor^2 > (\sqrt{n} - 1)^2 \ge n/2 + 1,$$so every integer from $0$ to $\lfloor n/2\rfloor$ is a difference of elements of $T_n$. but then their opposites are also differences, and thus all the integers $m$ satisfying$$-n/2 <  m \le n/2$$are differences of elements in $T_n$. Since every $k$ in $\mathbb{Z}_n$ is equal (mod $n$) to such an integer $m$, $T_n$ is a difference set. The set $T_n$ has $2\lfloor\sqrt{n}\rfloor - 1 < 2\sqrt{n}$ elements, and so we have $f(n) < 2\sqrt{n}$, for $n \ge 16$. This implies$${{\log f(n)}\over{\log n}} < {1\over2} + {{\log 2}\over{\log n}}.$$We can now use the squeeze theorem to conclude that$$\lim_{n \to \infty} {{\log f(n)}\over{\log n}} = {1\over2}.$$


text:
Q: Speculative execution Mapreduce/Spark I know Hadoop/Spark framework will detect failed or slow machines and execute the same tasks on different machine. How will (On what basis) framework identifies the
slow running machines. Is there any kind of stats for the framework to decide?
Can someone shed light some light here?

A: The MapReduce model is to break jobs into tasks and run the tasks in parallel to
make the overall job execution time smaller than it would be if the tasks ran
sequentially.
yarn.app.mapreduce.am.job.task.estimator.class- When MapReduce model lunch a new job this property and implementation is being used to estimate the task completion time at runtime. The estimated completion time for a task should be less than a minute. If a task is running beyond this estimated time it can mark as slow running task.
yarn.app.mapreduce.am.job.speculator.class - This property is being used
to implementing the speculative execution policy.

A: Spark.speculation   default value is false  If you set to "true", performs speculative execution of tasks. This means if one or more tasks are running slowly in a stage, they will be re-launched.

http://spark.apache.org/docs/latest/configuration.html
You can add these flags to your spark-submit, passing them under --conf  e.g.:
spark-submit \
--conf "spark.speculation=true" \
--conf "spark.speculation.multiplier=5" \
--conf "spark.speculation.quantile=0.90" \
--class "org.asyncified.myClass" "path/to/Vaquarkhanjar.jar"

Note :
Spark driver is spending a lot of time in speculation when managing a large number of tasks. enable it only if needed.


text:
Q: Promises in put request I have a route for put, and I use it like: axios.put('-SomeIp-/-SomeRoute-', SomeData);
Do I have to put .then after it or not?
In which cases do I use .then?

A: There's no requirement to register a callback for a promise.
If you don't want to run a function when it resolves, then don't tell it to run a function with then.


text:
Q: I need to make my app work in background even if its closed Im beginner with android, I want to make my app work a cyclic behavior in background even if it's closed.
Can someone help me?
Thanks!

A: You need to create a background service. Note that you also need to create a notification that will be visible during this service is running:
public class BgService extends Service {
    @Override
    public int onStartCommand(Intent i, int flags, int startId) {
        startForeground(C.MAIN_SERVICE_NOTIFICATION_ID, buildNotification(getString(R.string.service_title)));
        return START_NOT_STICKY;
    }

    protected Notification buildNotification(String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setTicker(getString(R.string.app_name))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(content)
                .setSmallIcon(R.drawable.notification_icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.app_icon))
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(false)
                .setOngoing(true)
                .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            builder.setPriority(Notification.PRIORITY_HIGH);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        return notification;
    }
}

You can start this service from your Application:
public class MyApp extends Application {
    @Override
    public void onCreate() {
        startService(new Intent(this, BgService.class));
    }
}


text:
Q: Why Is There No Retain Cycle In ReceiveValue Block Combine Subscription I'm determined to fully understand why this isn't causing a reference cycle. And in general what is happening at each stage of memory management here.
I have the following setup:
struct PresenterView: View {
    @State private var isPresented = false
    var body: some View {
        Text("Show")
            .sheet(isPresented: $isPresented) {
                DataList()
            }
            .onTapGesture {
                isPresented = true
            }
    }
}

struct DataList: View {

    @StateObject private var viewModel = DataListViewModel()

    var body: some View {
        NavigationView {
            List(viewModel.itemViewModels, id: \.self) { itemViewModel in
                Text(itemViewModel.displayText)
            }.onAppear {
                viewModel.fetchData()
            }.navigationBarTitle("Items")
        }
    }
}

class DataListViewModel: ObservableObject {

    private let webService = WebService()

    @Published var itemViewModels = [ItemViewModel]()

    private var cancellable: AnyCancellable?

    func fetchData() {
        cancellable = webService.fetchData().sink(receiveCompletion: { _ in
            //...
        }, receiveValue: { dataContainer in
            self.itemViewModels = dataContainer.data.items.map { ItemViewModel($0) }
        })
    }

    deinit {
        print("deinit")
    }

}

final class WebService {

    var components: URLComponents {
        //...
        return components
    }

    func fetchData() -> AnyPublisher<DataContainer, Error> {
        return URLSession.shared.dataTaskPublisher(for: components.url!)
            .map { $0.data }
            .decode(type: DataContainer.self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }
}

So when I create a PresenterView and then dismiss it I get a successful deinit print.
However I don't understand why they is no reference cycle here. DataListViewModel has cancellables which has a subscription that captures self. So DataListViewModel -> subscription and subscription -> DataListViewModel. How can deinit be triggered? In general is there a good approach to understanding whether there is a retain cycle in these kinds of situation?

A: The closure, as you expected, does retain a strong reference to self. The closure itself is maintained by the Sink subscriber.
If nothing else happens, this is a memory leak because the subscriber is never cancelled, because AnyCancellable is never released, because  self never de-inits, and self never de-inits because the subscriber is holding a reference it.
However, in your case, the publisher completes, and that's another way for the subscriber to release its closures. So, self is only released after the pipeline completes.
To illustrate, we can use a PassthroughSubject to explicitly send a completion:
class Foo {
   var c: AnyCancellable? = nil

   func fetch() {
      let subject = PassthroughSubject<String, Never>()

      c = subject.sink {
         self.c // capture self
         print($0)
      }

      subject.send("sync")

      DispatchQueue.main.async { subject.send("async") }

      DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
         subject.send("async 2 sec")
         subject.send(completion: .finished)
      }
   }

   deinit { print("deinit") }
}

do {
   Foo().fetch()
}

Because self is captured, it's not released until after a completion is sent 2 seconds later:
sync
async
async 2 sec
deinit

If you comment out the line subject.send(completion: .finished), there will not be a deinit:
sync
async
async 2 sec

If you use [weak self] in the closure, the pipeline would cancel:
sync
deinit


text:
Q: Unordered_map acts strange when I add a new element This lines are not working properly:
for (auto prod : productions_[*productionNonterm])
                productions_[nonterminal].push_back(prod);

If productions_[*productionNonterm] has only 1 element, everything is good. But if it has at least 2 elements, productionNonterm is modified and I have no idea why.
vector<string> nonterminals_;
unordered_map<string, vector<string>> productions_;

for (const auto &nonterminal : nonterminals_) {
    for (auto productionNonterm = productions_[nonterminal].begin(); productionNonterm != productions_[nonterminal].end(); ++productionNonterm) {
        if (cntNonterminalsInProduction(*productionNonterm) == 1 && cntTerminalsInProduction(*productionNonterm) == 0) {
            nonterminals_.erase(find(nonterminals_.begin(), nonterminals_.end(), *productionNonterm));

            for (auto prod : productions_[*productionNonterm])
                productions_[nonterminal].push_back(prod);

            productions_[*productionNonterm].erase(productions_[*productionNonterm].begin(), productions_[*productionNonterm].end());

            productions_[nonterminal].erase(productionNonterm);
            --productionNonterm;

        }
    }
}

A: problem with the iterator productionNonterm and it's getting invalidated during the loop:
once you start your loop
    for (auto prod : productions_[*productionNonterm])
        productions_[nonterminal].push_back(prod);

you'll get into with with a valid iterator (productionNonterm) pointing to a one (first) element in the productions_[nonterminal].
but after loop's body gets executed the first time - vector productions_[nonterminal] will reallocate its elements (due to growing) and your pointer (iterator) will be invalidated...

A: It is tricky modifying a collection while iterating it, and usually not worth the overhead to support it in the container.  In this case (vector) you are invalidating the iterator (i.e. a pointer to vector storage) as soon as the vector re-allocates when you grow it.
Have a look at vector::push_back, particularly the discussion of iterator validity.
In practice you can avoid this particular problem by sizing the vector but there are also issues keeping track of where you are putting new elements relative to the iterator, etc.  In general it leads to difficult-to-follow code, even when it is correct (or worse, looks it but has subtle issues).
I suggest you rewrite to a two-pass approach, collect up the elements to add or remove in one pass, then remove them etc.  Unless you have very good (and measured!) performance reasons to not do this, it's going to be easier to understand and maintain.  Recall that vector::erase can take a range.
It's also worth asking: does order matter here?  Should you be using std::unordered_set, in which case you wouldn't have this particular problem.
See what you think of that approach before "fixing" this one.


text:
Q: Blazor WASM client has become unstable in Large Spa I have a fairly large Blazor client WASM application.  Things were going great and I hit a wall.
After last week I seem to hit a wall.  Things that happen are:

*

*Some breakpoints don't work

*Debug build the server dies, which may be the cause of the above.

*Console.WriteLines don't work in chrome but seem to in Edge

*Unexpected Exceptions are thrown on will used services.

I think there is some other weirdness, but don't remember off the top of my head.  I am starting to think Blazor WASM isn't ready for prime time.
Has anyone else seen this?
How much data memory to Blazor have access to?
How large can the Blazor WASM code be?


text:
Q: How to sort gridview by column containing nullable integer? I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:
System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.
How do I customize the sorting or comparison logic to handle the null case?

A: The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:
gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
    // Only add custom handling for the sort expression on the
    // Nullable<int> column
    if (e.SortExpression == "MySortExpression")
    {
        // Convert datasource to a List<T>
        list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)
        {
            return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);
        }));

        // Bind the sorted list back to the gridview
    }
    else
    {
        // delegate to the gridview to handle its own sorting
    }
}

A: You could also override the null when you bind the data, placing a 0 instead.  Your answer is far better. :)
You could also make a custom type that overrides the Compare operator.  But that would just duplicate (and complicate) what you have above.


text:
Q: Grails insert date without time I have a date attribute in my domain and I want to insert to MySQL without time. getting exception  cannot cast string to date.Exception message:

Cannot cast object 2013-03-09 with class java.lang.String to class java.util.Date

I want to insert to the database without time.
Domain:
class Day {

Date date

        static mappings = {
        table name:'Days'

              date type: 'date'

    }

Controller:
def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
Date dateYmd = ymdFmt.format(today)

        day.date =dateYmd

A: day.date = new Date().clearTime()

clearTime() will reset the time portion to 00:00:00

A: I think you wan't to look at Date.parse http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse(java.lang.String, java.lang.String)
You can parse the date like.
String stringDate = '28/09/2010'
Date date = new Date().parse('d/M/yyyy', stringDate)

A: You should use java.sql.Date instead of java.util.Date.
The java.sql.Date class corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally java.sql.Date isn't tied to timezones.
For a good explanation about the two see java.util.Date vs java.sql.Date


text:
Q: Where in the linux kernel does "mmap" looks at the file inode to see if it's already loaded? I want to kprobe the function that maps new files onto the memory, but i'm having difficulty finding the function that checks if the file descriptor is already loaded.
I tried hooking the mmap syscall but that's not really helping because I get already mapped files like libc.so.
I can't seem to figure out if it's filesystem related or memory related, I looked in both places and can't find where it happens.

A: The inode is a kernel-private object.  The kernel does not use libc.so.   User level programs (which may use libc.so) cannot directly reference inodes; instead they have a process local identifier (a file descriptor) which the kernel knows how to translate to the appropriate structure.
So, you are looking in the wrong place.


text:
Q: Community URL Fragment Identifier seems to prevent query execution when setting a default queryString I have a custom search component that executes a query on keypress - this triggers a force:navgatetourl event. My query string contains, a query, and a fragment identifier with custom parameters that will then be used by other components on the search page.
However, my query execution method seems to only work after a second keypress. The initial one results in a URL change which is reflected in the community, however, the page navigation never occurs until a second keypress (enter) is entered. This would seem liek a bug at a first glance, however, if someone notices what I might be doing wrong, feel free to post an answer.
I am properly encoding my url prior to navigating. Here is a minimal reproduceable code sample.
SearchInput.cmp

    <aura:attribute name='searchInut' type='String' default='' access='global' />

    <div class="search-container" onkeyup="{!c.handlekeyPress}">
        <lightning:input aura:id="query-box" id="query-box" type="search" name="search" placeholder="additional search terms" value="{!v.searchInut}"/>
    </div>
</aura:component>

SearchInputController.js
    ({
    handlekeyPress  : function(cmp, event, helper) {
        console.log('Keypress--->')
        const theQuery = cmp.find('query-box').get('v.value');
        if(event.which==13){
            console.log('Try to execute on Enter--->')
            helper.executeQuery(cmp, event, theQuery)
        }
    },

})

SearchInputHelper.js
({
executeQuery : function(cmp, event, theQuery){
    console.log('in helper -- Should trigger query')
    const queryUrl = `/global-search/example-search-term#q=${theQuery}&t=All&sort=relevancy`;
    const theEncodedUrl = encodeURI(queryUrl);
    let urlEvent = $A.get("e.force:navigateToURL");
    urlEvent.setParams({
        "url": theUrl
    });
    urlEvent.fire();
    console.log('Navigation Event Fired / Should have fired');
    },
})

Last minute update: While Creating this post I noticed that if I remove or change my default query (example-search-term) to a query dynamically (using string literals or concatenation) the search works normally.
This works:
const queryUrl = `/global-search/${theQuery+'#q='+theQuery}&t=All&sort=relevancy`;

So - updated question would be why setting a default query seems to prevent the initial navigation event. (looks like a bug)


text:
Q: Regex - multiple matches How to fix this regex in order to get the mentioned outcome ?
regex: (0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[(?:M|V|P)(?:[^\[])*])
string: LCR005B"*ADM-CID"9876R579BDFL789ABC#12345A[4D32FC2B12345A|113002065][Vanydata][M1234567890AB][Panydata]
outcome should be:

*

*005B

*"*ADM-CID"

*9876

*R579BDF

*L789ABC

*#12345A

*[4D32FC2B12345A|113002065]

*[Vanydata]

*[M1234567890AB]

*[Panydata]

Later edit:
This currently outputs:

*

*005B

*"*ADM-CID"

*9876

*R579BDF

*L789ABC

*#12345A

*[4D32FC2B12345A|113002065]

*[Vanydata]

A: This is your regex:
(0(?:[0-9]|[A-F]){3})
(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")
(\d{4})
(R?(?:[0-9]|[A-F])*)
(L[^#]*)
(#[^\[]*)
(\[[^\[]*)
(\[(?:M|V|P)(?:[^\[])*])

You do have only 8 capturing groups, none is repeated, why do you think this should output 10 groups?
OK, Because of the (?:M|V|P) of the last group, it would be able to match the content of the 3 last square brackets, but this group is not repeated, so it will match only the first one.
You have 2 possibilities.

*

*Put a quantifier behind the last group
(0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[(?:M|V|P)(?:[^\[])*])+

or
(0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[(?:M|V|P)(?:[^\[])*]){3}

this will now match the string till the end, but there are still only 8 capturing groups and the content of the last one is now not "[Vanydata]" anymore, its the last match of this group "[Panydata]"

*Add two more groups to your regex
(0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[(?:M|V|P)(?:[^\[])*])(\[(?:M|V|P)(?:[^\[])*])(\[(?:M|V|P)(?:[^\[])*])

This does now have 10 capturing groups and the result is as you expected. If the Starting letter of those 3 last groups is always the same for each group you can simplify it to
(0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[V(?:[^\[])*])(\[M(?:[^\[])*])(\[P(?:[^\[])*])

See it here on Regexr
Update
You can make something optional by adding a question mark after it
(0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[[VMP](?:[^\[])*])?(\[[VMP](?:[^\[])*])?(\[[VMP](?:[^\[])*])?

See it here on Regexr, hovering over the match shows you the content of the capturing groups.

A: Well, the problem seems to be the last Regex capture group. (\[(?:M|V|P)(?:[^\[])*]) doesn't seem to work.
This Regex capture group \[(\w.*|(M|V|P)\d{10}AB)\] catches your last 3 bracketed words.
Complete regex: (0(?:[0-9]|[A-F]){3})(\"\*?(?:SIA-DCS|ADM-CID|NULL)\")(\d{4})(R?(?:[0-9]|[A-F])*)(L[^#]*)(#[^\[]*)(\[[^\[]*)(\[(\w.*|(M|V|P)\d{10}AB)\])


text:
Q: Sequelize throwing: "relation "users" does not exist" I have a User model that has a hasMany association with my Item model:
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    underscored: true,
  });
  User.associate = function(models) {
    // associations can be defined here
    User.hasMany(models.Item, {
      onDelete: 'CASCADE'
    })
  };
  return User;
};

And I have an Item model that belongs to User:
module.exports = (sequelize, DataTypes) => {
  const Item = sequelize.define('Item', {
    title: DataTypes.STRING,
    link: DataTypes.STRING,
    user_id: DataTypes.INTEGER
  }, {
    underscored: true,
  });
  Item.associate = function (models) {
    // associations can be defined here
    Item.belongsTo(models.User)
  };
  return Item;
};

When I execute User.findAll()
I get the error relation "users" does not exist.
Here is the raw SQL that is executed:
SELECT
  "User"."id", "User"."first_name", "User"."last_name", "User"."email",
  "User"."created_at" AS "createdAt", "User"."updated_at" AS "updatedAt",
  "Items"."id" AS "Items.id", "Items"."title" AS "Items.title",
  "Items"."link" AS "Items.link", "Items"."user_id" AS "Items.user_id",
  "Items"."created_at" AS "Items.createdAt", "Items"."updated_at" AS "Items.updatedAt",
  "Items"."user_id" AS "Items.UserId"
FROM "users" AS "User"
LEFT OUTER JOIN "items" AS "Items" ON "User"."id" = "Items"."user_id";

Items attributes are prepended by "Items" which is correct but Users is prepended by "User" which is not correct. Also not sure why it says FROM "users" AS "User" instead of FROM "Users"
In my config I used underscored: true and I'm using a postgres database. There is a "Users" table and an "Items" table in my postgres database.
"pg": "^7.12.1",
"sequelize": "^5.18.4"
"sequelize-cli": "^5.5.1"

A: Switch the config/config.js from:
require('dotenv').config()

module.exports = {
  development: {
    url: process.env.DEV_DATABASE_URL,
    dialect: 'postgres'
  }
}

to:
require('dotenv').config()

module.exports = {
  development: {
    url: process.env.DEV_DATABASE_URL,
    database: 'database_development',
    dialect: 'postgres'
  }
}

Sequelize requires a database key in the config!
https://github.com/sequelize/cli/blob/77a9a76420e36cfbcb82fe3c9c6a12d52c768104/src/commands/database.js#L88


text:
Q: Проблема с настройкой сети: не могу сделать ping самого себя Доброго времени суток.
Пишу свое приложение Server и Client. Есть проблема с подключением к Server. А именно при connect в Client происходит ошибка: сеть не доступна.
При попытке сделать ping своего внешнего IP адреса происходит ошибка: сеть недоступна.
Как решить эту проблему?
Upd:
Прилагаю вывод команды ip a, ip r, свой внешний ip
IP : 176.100.250.16

A: ваш «внешний» ip-адрес присутствует в приведённой вами информации: 10.104.4.156.
ваш «внутрениий» ip-адрес даже не нужно нигде «подсматривать». это 127.0.0.1.
если написанный вами «сервер» сконфигурирован прослушивать подключения на всех интерфейсах, то написанный вами «клиент», будучи запущенным на этой же машине, может подключаться к любому из этих двух адресов.

а тот адрес, который вы считаете «внешним», к вашему компьютеру, скорее всего, не имеет никакого отношения. это один из множества ip-адресов, используемых вашим интернет-провайдером. если этот адрес (согласно договору) закреплён за вами, то он должен ретранслироваться (провайдером) на ваше оборудование, подключенное непосредственно к сети провайдера. вероятно, это какой-нибудь маршрутизатор. и чтобы по этому адресу можно было «достучаться» до вашей машины, потребуется некоторая настройка вашего маршрутизатора. посмотрите этот ответ (и ссылки в нём).


text:
Q: jQuery iframe onload I have an iframe that represents the content of my main page and it loads a different src depending on the menu option chosen. I want to perform a series of actions as soon as the iFrame is loaded but I cant seem to get it to work. The code looks more or less like the following:
$(document).ready(function () {

    $('#navigation').load(function () {
        alert('frame loaded!')
    });
});

A: .load for event binding was deprecated in jQuery 1.8, use .on("load" instead.

A: I asume this function is in your iFrame and will be executed after the document loading. If not - ther is some conceptual error. Anyway - the load function in jQuery will try to load a html document or piece of it in the object you specify - http://api.jquery.com/load/


text:
Q: Can Bearer token validate Message Extension request from MS Teams? I created a message extension for an App within Microsoft Teams that when clicked sends the message from Teams to my web service.
(one of these https://learn.microsoft.com/en-us/microsoftteams/platform/messaging-extensions/how-to/action-commands/define-action-command)
I don't need to authenticate the user, but I want to authenticate that the incoming request came from Microsoft instead of someone maliciously sending me data.
The Authentication method described by Microsoft here; authenticates the user individually on the system. Which I don't want as the user might not have an account.
There is a Bearer token in the header of the action's incoming request to my web service. Can I somehow utilize this to validate it?

A: You shouldn't validate the Bearer token sent from MS Teams to your MS Teams App.
The right way to do it is use the "client credentials grant" between your MS Teams app and your web service. The grant is described here: https://www.rfc-editor.org/rfc/rfc6749#section-4.4
Your MS Teams App will be the client. Each request your client sends to your web service will contain a token issued by either your web service or an external identity provider your web service trusts. This token will be validated by your web service to ensure the request is genuine.
This grant is suitable for service-to-service communication you described.


text:
Q: Could i use only results without interface with google custom search api? could i use custom search engine without interface in my apps?
I already checked the documents but it doesn't explain about that.
i already asked to help center but no answer yet.
i only need results.
please if you know, help me.

A: Yes--that's precisely what the Custom Search JSON API is for.
https://developers.google.com/custom-search/v1/overview


text:
Q: Scala: Overriding equals for value classes To get more type safety in our code base we have started to replace generic Strings, Ints etc. with type safe value classes, but I am struggling to get them working conveniently with the == operator and literals. Hopefully someone can help me out.
Our value classes are defined and used like this:
case class Name(value: String) extends AnyVal {}
object Name { implicit def to(something:String): Name = Name(something) // convenience }

case class Address(value: String) extends AnyVal {}
object Address { implicit def to(something:String): Address = Address(something) // convenience }

case class Person(name: Name, address: Address) {
  def move(newAddress: Address) = copy(address=newAddress)
}
val somebody = Person("Pete", "Street 1")

somebody.move(Address("Street 2")) // allowed
somebody.move(somebody.name) // not allowed, which is exactly what we want
somebody.move("Street 2") // allowed by convenience

Now, I would like them to compare "naturally" on their inner value:
Name("Pete") == "Pete" // should be true, but evaluates to False

I can sort of fix this by overriding equals like this:
case class Name(value: String) extends AnyVal {
  override def equals(other: Any) =
    if (other.isInstanceOf[Name])
      other.asInstanceOf[Name].value == this.value
    else if (other.isInstanceOf[String])
      other == this.value
    else
      false
}

Name("Pete") == "Pete" // now evaluates to true

However, this solution is not symmetric:
"Pete" == Name("Pete") // evaluates to false, because it is using String.equals

I do not know how to fix this. Not even declaring an implicit conversion from Name to String helps (and I would much prefer not to have such a thing). Is it possible to do what I am trying to do?
EDIT: I probably failed to be clear on this, but I am not really looking for advice on software development. This is meant to be a technical question: Can it be done in Scala or not?
I have some reasons for doing what I have described, but sadly they relate to a codebase of tens of thousands of lines of Scala code, and cannot be conveyed in a short stack overflow question.

A: I think, you should just get rid of your convenience implicits instead. They defeat the purpose:
 val john = Person("Street 1", "John") // mixed up order
 john.move("Pete") // Yup, I can "move" to a name ...

Now, john is someone named "Street 1", and living at address "Pete". This isn't something that you want to be allowed after going with the trouble of defining all the value classes.

A: I don't think == can be made to work in this situation. What you might do is define a different comparison operation.
case class Name(value: String) extends AnyVal {
  def is(n: Name): Boolean = value == n.value
}

You'll also have to broaden the scope of the implicit converter so that it can be accessed for these conversions.
implicit def toName(something:String): Name = Name(something) // not in object

Now this works.
val somebody = Person("Pete", "Street 1")
somebody.move(Address("Street 2")) // allowed
somebody.move("Street 2") // allowed by convenience
somebody.name is "Pete"   // true
"Pete" is somebody.name   // true


text:
Q: Como extrair dados em forma de índices deste array? Estou desenvolvendo um site para imobiliária e vou usar o recurso de REST. O código abaixo me retorna um por um os imóveis cadastrados no software do servidor conforme pode ser visto aqui.
$dados = array(
    'fields'    =>
        array(
            'Codigo', 'Cidade', 'Bairro', 'ValorVenda'
    ),
    'paginacao' =>
        array(
            'pagina'        => 1,
            'quantidade'    => 10
    )
);

$key         =  'c9fdd79584fb8d369a6a579af1a8f681';
$postFields  =  json_encode( $dados );
$url         =  'http://sandbox-rest.vistahost.com.br/imoveis/listar?key=' . $key;
$url        .=  '&showtotal=1&pesquisa=' . $postFields;

$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER , array( 'Accept: application/json' ) );
$result = curl_exec( $ch );

$result = json_decode( $result, true );

echo '<pre>';
    print_r( $result );
echo '<pre>';

A minha pergunta é: neste caso, como extrair um por um dos dados dos arrays de imóveis em forma de índices?
O que eu sei é que o $result tá guardando tudo dentro dele e ao colocar um print_r ele solta os imóveis. Como desmembrar estas informações em forma de índices, alguma coisa do tipo:
echo $result['fields']['Codigo'];

O print_r($result) imprime isto:
Array
(
    [62] => Array
        (
            [Codigo] => 62
            [Cidade] => Porto Alegre
            [Bairro] => Espirito Santo
            [ValorVenda] => 105000
        )

    [69] => Array
        (
            [Codigo] => 69
            [Cidade] => Porto Alegre
            [Bairro] => Central
            [ValorVenda] => 90000
        ) ...

A: Essa questão é muito estranha, já que a resposta é bem óbvia.
Ora, você sempre precisará especificar um índice para um determinado registro do qual você quer obter alguma informação:
$registro = $results[62];
print $registro['ValorVenda'];

Mesmo dentro de um loop como foreach, o índice para cada registro é implicitamente considerado:
foreach ($results as $result) {
    print $result['Bairro'] . PHP_EOL;
    print $result['ValorVenda']. PHP_EOL;
    print "---" . PHP_EOL;
}


text:
Q: Show files in folder while using FolderPicker Is there any possible way to show the files in the folders when using FolderPicker ?
Code :
FolderPicker folderPicker = new FolderPicker();
folderPicker.ViewMode = PickerViewMode.Thumbnail;
folderPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
folderPicker.FileTypeFilter.Add("*");

return await folderPicker.PickSingleFolderAsync();

A: If you use the WindowsAPICodepack, you can do it like so:
var openFolder = new CommonOpenFileDialog();
openFolder.AllowNonFileSystemItems = true;
openFolder.Multiselect = true;
openFolder.IsFolderPicker = true;
openFolder.Title = "Select folders.";

if (openFolder.ShowDialog() != CommonFileDialogResult.Ok)
{
    MessageBox.Show("No folder selected.");
    return;
}

// get all the directories in selected directory
var dirs = openFolder.FileNames.ToArray();

However if you're using just Windows.Storage.Pickers, the code you've provided is the example given on the Microsoft docs (https://learn.microsoft.com/en-us/uwp/api/windows.storage.pickers.folderpicker), so I'm not too sure why that doesn't work.

A: For the built-in FolderPicker, it's impossible. You could call the 'StorageFolder.GetFilesAsync' method to get the files in the current folder.
FolderPicker folderPicker = new FolderPicker();
folderPicker.ViewMode = PickerViewMode.List;
folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
folderPicker.FileTypeFilter.Add("*");

var folder = await folderPicker.PickSingleFolderAsync();

foreach (var files in await folder.GetFilesAsync())
{
    Debug.WriteLine(files.DisplayName);
}

If you want to show these files on the UI, you could choose some list controls to show them. For example, List view and grid view.


text:
Q: gap appearing between table-cell-display divs after zooming I am experiencing a very unusual bug with chrome. basically, I have 2 div's with table-cell displays. One has text in it the other an input. What happens is when the page is zoomed in and then zoomed out again. a gap appears between the top of the input and the top border, and each time the page is zoomed in and out the gap gets bigger and bigger. If both div's have only text or both have inputs, then it's OK.setting the divs height makes no difference. No such problem with FF. here is a little diagram to illustrate.
It start's like this:
                .--------.--------.
                .  text  . |input|.
                .--------.--------.

after zooming in and out sereral times, it looks like this:
                . -------.--------.
                .        .        .
                .        .        .
                .  text  . |input|.
                .--------.--------.

here is the code:
.border{
         border:1px solid grey;
         display:table-cell;
       }

text

<input />

does anyone have any idea why this might be happening, and what can be done to prevent it? Thanks.

A: Try like this, it will help you...
  .border
   {
     border:1px solid grey;
     display:table-cell;
     text-align: center;
     vertical-align: middle
   }


text:
Q: How to submit Form by Bootstrap Modal using Ajax I'll try to be concise as possible, i am new to bootstrap and advanced javascript, basically i have used bootstrap modal to load a form in front of user to collect and save data in database.  my question is how will you do that using ajax, because i have other modals also which will have different forms and  i dont want to process the entire page again and again.
P.S
i am making this application in codeigniter
This is the form inside modal

Unit Details

                <button type="button" class="close" data-dismiss="modal" style="margin-top: -20px;">&times</button>

 <?php echo form_open('setupnewblock/registerNewBlock'); ?>

                Address 1
                <input  type="text" placeHolder="" name="address1" style="width: 219px; height: 17px; margin-left: 20px; margin-top: 3px;" value="<?php echo set_value('address1'); ?>"/>

                Address 2
                <input  type="text" placeHolder="" name="address2" style="width: 219px; height: 17px; margin-left:20px; margin-top: 3px;" value="<?php echo set_value('address2'); ?>"/>

                Address 3
                <input  type="text" placeHolder="" name="address3" style="width: 219px; height: 17px; margin-left:20px; margin-top: 3px;" value="<?php echo set_value('address3'); ?>"/>

          <input type="submit" value="Save" name="save" class="btn btn-primary" style="margin-top: 2px;  height: 27px; width: 89px;" data-dismiss="modal"></input>
          <?php echo form_close(); ?>

i want to submit this form using ajax

A: i've got same problem, but when I tried this gist all done nicely.
you can try this code:
$(document).ready( function() {
    $('.modal form').on('submit', function(event) {
        event.preventDefault()
        $.post( $(this).attr('action'), $(this).serialize(), function(data) {
            // just try to see the outputs
            console.log(data)
            if(data.return===true) {
                // Success code here
            } else {
                // Error code here
            }
        }, 'json')
    })
});

A: If you want to do it very simple this should work for you:
$('input[name=save]').click(function(e) {
    e.preventDefault();

    $.post("setupnewblock/registerNewBlock", {form: $("#launch form").serialize()},
        function(data) {
        // callback
    });
});

A: Have a look at codeigniter user guide :
so your code should be ,
$attributes = array('class' => 'myform', 'id' => 'myform');
    echo form_open('setupnewblock/registerNewBlock', $attributes);

And After that you have to bind the submit function of your form to jquery function like
$(document).ready(function() {
    $("#myform").submit(function() {

        $.ajax(
                {
                    type: 'POST',
                    url: 'your url to php file',
                    data: {}, //your form datas to post
                    success: function(response)
                    {
                        alert(response);

                    },
                    error: function()
                    {
                        alert("Failure");
                    }
                });

    });
});


text:
Q: What is in the future for REVU Now that there is the Post Release Apps Process in place and there is a big push to get new software into Ubuntu, what are the future plans for REVU?
Will there be an application review board for REVU or will it remain what it is now, hit and miss at best.

A: There are no plans to change REVU.  It is still meant to be the way to get an application into the repos and have it stay there from release to release.  The ARB is only for applications that are going in for a single already-stable release.
REVU would be less hit-or-miss if the submissions were better though :-/  Many of the packages sit there with comments saying "you need to fix foo" for months and no new uploads with those fixes happen.

A: I'm not aware of any immediate plans for technical changes in REVU and the new package submission process, but one significant policy change for new packages in recent times is that the primarily recommended way to get a new package into Ubuntu if you want to be the person who is responsible for it (as opposed to team maintenance) is now to do it through Debian.


text:
Q: When click on second dropdown black box should remain visible In this dropdown nav I'm building if a dropdown is opened and you click to open a second one, the black box should remain visible. At the moment the black box disappears when you click on a second dropdown and reappears after the dropdown is completely opened.
Update
I also noticed the black box shows after a dropdown is open and it should open at the same time.
I hope this makes sense and thank you for your help!

$(document).ready(function() {
  $(".click").on("click", function(e) {
    var menu = $(this);
    toggleDropDown(menu);
  });

  $(document).on('mouseup',function(e) {
    var container = $("nav .top-bar-section ul");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
      $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
        $(".main-container").removeClass("black-bg");
        if ($('a.active').hasClass('active')) {
          $('a.active').removeClass('active');
        }
      });
    }
  });

});

function toggleDropDown(menu) {
  var isActive = $('a.active').length;
  $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
    $(".main-container").removeClass("black-bg");
    if (menu.hasClass('active')) {
      menu.removeClass('active');
    } else {
      $('a.active').removeClass('active');
      menu.addClass('active');
      menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
        $(".main-container").addClass("black-bg");
      });
    }
  });
  if (!isActive) {
    menu.addClass('active');
    menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
      $(".main-container").addClass("black-bg");
    });
  }

}
* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

.nav-wrapper {
    width: 100%;
    overflow: hidden;
    background: #424242;
}

nav {
    width: 1024px;
    margin: auto;
    overflow: hidden;
    background: #424242;
}

.nav-content {
    width: 100%;
    z-index: 999;
    background: #ccc;
}

.top-bar-section {
    float: left;
}
.top-bar-section a.active {
    background: #f00;
}

.showup {
    display: none;
    background: #ccc;
    position: absolute;
    width: 100%;
    top: 70px;
    left: 0;
    z-index: 99;
    padding: 30px 15px 30px 20px;
}

p {
    font-size: 14px;
    line-height: 1.4;
}

li.nav-item {
    display: inline-block;
    background: #f5f5f5;
}
li.nav-item a {
    display: block;
    text-decoration: none;
    padding: 10px;
}
.main-container {
    width: 80%;
    height: 400px;
    margin: auto;
}
.black-bg {
    background: #000;
}

          Nav item 1

                Dropdown for Nav Item 1.

          Nav item 2

                Dropdown for Nav Item 2.

          Nav item 3

                Dropdown for Nav Item 3.

          Nav item 4

                Dropdown for Nav Item 4.

A: If you want black-bg being added once the menu is clicked, then do not remove and add black-bg class on every click event. Simply add it once if the menu have active class and remove it when menu do not active class. If you remove and add class on every click event then black-bg will first disappear and again it will appear. To black-bg at the time drop-down is open then remove $(".main-container").addClass("black-bg"); from callback function of slideDown() because a callback function is executed after the current effect is finished.

$(document).ready(function() {
  $(".click").on("click", function(e) {
    var menu = $(this);
    toggleDropDown(menu);
  });

  $(document).on('mouseup',function(e) {
    var container = $("nav .top-bar-section ul");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
      $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
        $(".main-container").removeClass("black-bg");
        if ($('a.active').hasClass('active')) {
          $('a.active').removeClass('active');
        }
      });
    }
  });

});

function toggleDropDown(menu) {
  var isActive = $('a.active').length;
  $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
    if (menu.hasClass('active')) {
      menu.removeClass('active');
      $(".main-container").removeClass("black-bg");
    } else {
      $('a.active').removeClass('active');
      menu.addClass('active');
      menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
       });
    }
  });
  if (!isActive) {
    menu.addClass('active');
    menu.parent().find('.showup').stop(true, true).slideDown(500);
    $(".main-container").addClass("black-bg");
  }

}
* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

.nav-wrapper {
    width: 100%;
    overflow: hidden;
    background: #424242;
}

nav {
    width: 1024px;
    margin: auto;
    overflow: hidden;
    background: #424242;
}

.nav-content {
    width: 100%;
    z-index: 999;
    background: #ccc;
}

.top-bar-section {
    float: left;
}
.top-bar-section a.active {
    background: #f00;
}

.showup {
    display: none;
    background: #ccc;
    position: absolute;
    width: 100%;
    top: 70px;
    left: 0;
    z-index: 99;
    padding: 30px 15px 30px 20px;
}

p {
    font-size: 14px;
    line-height: 1.4;
}

li.nav-item {
    display: inline-block;
    background: #f5f5f5;
}
li.nav-item a {
    display: block;
    text-decoration: none;
    padding: 10px;
}
.main-container {
    width: 80%;
    height: 400px;
    margin: auto;
}
.black-bg {
    background: #000;
}

          Nav item 1

                Dropdown for Nav Item 1.

          Nav item 2

                Dropdown for Nav Item 2.

          Nav item 3

                Dropdown for Nav Item 3.

          Nav item 4

                Dropdown for Nav Item 4.

A: Just move $(".main-container").removeClass("black-bg"); into if (menu.hasClass('active')) {

$(document).ready(function() {
  $(".click").on("click", function(e) {
    var menu = $(this);
    toggleDropDown(menu);
  });

  $(document).on('mouseup',function(e) {
    var container = $("nav .top-bar-section ul");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
      $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
        $(".main-container").removeClass("black-bg");
        if ($('a.active').hasClass('active')) {
          $('a.active').removeClass('active');
        }
      });
    }
  });

});

function toggleDropDown(menu) {
  var isActive = $('a.active').length;
  $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
    //$(".main-container").removeClass("black-bg"); FROM HERE
    if (menu.hasClass('active')) {
      menu.removeClass('active');
      $(".main-container").removeClass("black-bg"); // TO HERE
    } else {
      $('a.active').removeClass('active');
      menu.addClass('active');
      menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
        $(".main-container").addClass("black-bg");
      });
    }
  });
  if (!isActive) {
    menu.addClass('active');
    menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
      $(".main-container").addClass("black-bg");
    });
  }

}
* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

.nav-wrapper {
    width: 100%;
    overflow: hidden;
    background: #424242;
}

nav {
    width: 1024px;
    margin: auto;
    overflow: hidden;
    background: #424242;
}

.nav-content {
    width: 100%;
    z-index: 999;
    background: #ccc;
}

.top-bar-section {
    float: left;
}
.top-bar-section a.active {
    background: #f00;
}

.showup {
    display: none;
    background: #ccc;
    position: absolute;
    width: 100%;
    top: 70px;
    left: 0;
    z-index: 99;
    padding: 30px 15px 30px 20px;
}

p {
    font-size: 14px;
    line-height: 1.4;
}

li.nav-item {
    display: inline-block;
    background: #f5f5f5;
}
li.nav-item a {
    display: block;
    text-decoration: none;
    padding: 10px;
}
.main-container {
    width: 80%;
    height: 400px;
    margin: auto;
}
.black-bg {
    background: #000;
}

          Nav item 1

                Dropdown for Nav Item 1.

          Nav item 2

                Dropdown for Nav Item 2.

          Nav item 3

                Dropdown for Nav Item 3.

          Nav item 4

                Dropdown for Nav Item 4.

A: Is this what you are looking for?
$(document).ready(function() {
  $(".click").on("click", function(e) {
    var menu = $(this);
    toggleDropDown(menu);
  });

  $(document).on('mouseup',function(e) {
    var container = $("nav .top-bar-section ul");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
      $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
        $(".main-container").removeClass("black-bg");
        if ($('a.active').hasClass('active')) {
          $('a.active').removeClass('active');
        }
      });
    }
  });

});

function toggleDropDown(menu) {
  var isActive = $('a.active').length;
  $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
    if (menu.hasClass('active')) {
      menu.removeClass('active');
    } else {
      $('a.active').removeClass('active');
      menu.addClass('active');
      menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
        $(".main-container").addClass("black-bg");
      });
    }
  });
  if (!isActive) {
    menu.addClass('active');
    menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
      $(".main-container").addClass("black-bg");
    });
  }

The black box will remain there in this case. What you were previously doing was that you were removing black-box explicitly.


text:
Q: Module index page redirection not working in YII i am new user to yii framewrok.i added one new module in the name coupon for admin side(in admin folder) in YII framework. the default index page is loading fine which is in the path of app/desig/admin/default/site/home.php
but when i try to access app/desig/admin/default/coupon/index.php . it wont redirect to that page. empty white page is loaded.
what is the issue?. how can i solve this?.

A: Did you specify the coupon module in the modules field of the configuration array in config/main.php? And did you import the model classes in the import field? Doing both of these should make it work.


text:
Q: The given key was not present in the dictionary exception I have a websocket server writed in c#C#. When i'm handling a packet from client in the server I get the error:
The given key ´4´ was not present in the dictionary.
This key exist. Other keys doesn't has this problem. The code pass the if statement.
string rawdata = Encoding.UTF8.GetString(decoded);
string[] msgdata = rawdata.Split("--");

int funcId = int.Parse(msgdata[0]);

if (Server.packetHandlersWS.ContainsKey(funcId)) {
    Server.packetHandlersWS[funcId](id, msgdata);
}

I tried cleanup on my project, i've tried delet the .pdb files in the project and rebuild. None of this fixes the problem.

A: Because packetHandlersWS is Dictionary<,> (from comments), there's a very good chance that you've corrupted the internal state, because you aren't doing any synchronization - and Dictionary<,> is not thread-safe. If this is the case, there's a very real chance that switching to ConcurrentDictionary<,> will fix this (note: you should still use TryGetValue with ConcurrentDictionary<,>, to avoid another race condition).


text:
Q: Rename table data field in mysql  Chart_date     chart_field                                          chart_counts
  20131115      user_jrFeed_item_count ,                              {"1":2}
  20131115      user_jrForum_item_count,                              {"1":1}
  20131115      user_jrFeed_item_count,user_jrForum_item_count,       {"1":1,"1":2}

How can I rename the text "user_jrFeed_item_count,user_jrForum_item_count" to something like "song_file_stream_count" in mysql?
The field:  20131115   user_jrFeed_item_count,user_jrForum_item_count,    {"1":1,"1":2}
is created from this function
INSERT INTO table1  (Chart_date, chart_field, chart_counts)
SELECT Chart_date,   GROUP_CONCAT(chart_field ) as chart_field,
REPLACE(GROUP_CONCAT(chart_counts),'},{',',') as chart_counts
FROM table1
GROUP BY Chart_date

A: You need to add another column(SrNo) that should act as an auto-incremental one and consider it your primary key. The use the update statement :
UPDATE TABLE SET chart_field = "song_file_stream_count" WHERE SrNo = 2;

A: The fields aren't created by that statement. That statement is just inserting into an aggregation table, which is what you asked on this question.
Besides, you don't really need to change field names. You are looking for a way to replace the field's values, which is different.
You might run @Aakash Goyal update statement, but keep in mind that any new records created on Chart_date or table1 will come in the current format. You either need to keep updating the records OR just replace them when you query the table.
SELECT  Chart_date   ,
        replace(chart_field,
                'user_jrFeed_item_count,user_jrForum_item_count,',
                'song_file_stream_count') as chart_field,
        chart_counts
FROM table1


text:
Q: Number of possible sets for given N How many possible valid collections are there for a given positive integer N given the following conditions:
All the sums from 1 to N should be possible to be made by selecting some of the integers. Also this has to be done in way such that if any integer from 1 to N can be made in more than one way by combining other selected integers then that set of integers is not valid.
For example, with N = 7,
The valid collections are:{1,1,1,1,1,1,1},{1,1,1,4},{1,2,2,2},{1,2,4}
Invalid collections are:
{1,1,1,2,2} because the sum adds up to 7 but 2 can be made by {1,1} and {2}, 3 can be made by {1,1,1} and {1,2}, 4 can be made by {1,1,2} and {2,2} and similarly 5, 6 and 7 can also be made in multiple ways using the same set.
{1,1,3,6} because all from 1 to 7 can be uniquely made but the sum is not 7 (its 11).

A: These are perfect partitions given in OEIS.  a(n-1) = sum of all a(i-1) such that i divides n and i < n.

A: The term I would use is "multiset".  Note that your multiset must contain 1 (as this is the only way to get a sum of 1).   Suppose there are $r$ different values $a_1 = 1, \ldots, a_r$ in the multiset, with $k_j$ copies of $a_j$.  Then we must have $a_j = (k_{j-1}+1) a_{j-1}$ for $j = 2, \ldots, r$, and $N = (k_r + 1) a_r - 1$.  Working backwards, if $A(N)$ is the number of valid multisets summing to $N$, for each factorization $N+1 = ab$ where $a$ and $b$ are positive integers with $b > 1$ you can take $a_r = a$, $k_r = b - 1$, together with any valid multiset summing to $a-1$.  Thus $A(N) = \sum_{b | N+1, b > 1} A((N+1)/b - 1)$ for $N \ge 1$, with $A(0) = 1$.  We then have, if I programmed it right,  1, 1, 2, 1, 3, 1, 4, 2, 3, 1, 8, 1, 3, 3, 8, 1, 8, 1, 8, 3 for $N$ from 1 to 20.  This matches OEIS sequence A002033, "Number of perfect partitions of n".

A: Suppose your collection contains a finite set of distinct numbers $\{n_1 ... n_k\}$ and that the collection contains the number $n_i$ $t_i$ times (you can also suppose that the $n_i$ are sorted)
Then your condition is that for every number $x$ between 0 and $N$, $x$ can be written as $x = \Sigma u_i n_i$ with $0 \leq u_i \leq t_i$ in exactly one way.
This is possible if and only if $n_1 = 1$, forall $i$, $n_i = \Sigma_{j\lt i} t_i n_i$, and $N = \Sigma t_i n_i$.
You can prove this by doing an induction on $k$, starting at $k=N=0$ for the base case.
The base case is easy. The induction case is not difficult :
If you have a valid collection containing $k$ distinct terms that can make all numbers up to $N_k$, then the only way to extend it into a bigger collection is by adding $n_{k+1} = N_k+1$.
If you pick a smaller number, then $n_{k+1}$ can be written in two ways, if you pick a bigger number, then you can not make $N_k+1$.
And then, if you have a valid collection made of $k+1$ terms, then the sub-collection containing the first $k$ distinct terms is also valid and has to write every number up to $n_{k+1}-1$ for the same kind of reasons.
Thus, a valid collection of $k$ distinct terms that makes every number up to $N$ is determined by the sequence $(n_1=1, \ldots n_k, n_{k+1}=N+1)$ where $n_i$ divides $n_{i+1}$ :
 $$n_i = \Sigma_{j \lt i} t_j n_j = n_{i-1} +  t_{i-1} n_{i-1} = (t_{i-1} + 1) n_{i-1}$$
So this shows why they are successives multiples of each other and how to recover the $t_i$ from the sequence.
The 4 collections you gave as an example correspond respectively to the sequences $(1,8), (1,2,8), (1,4,8), (1,2,4,8)$.
The number of valid sequences depends on the exponents in the prime decomposition of $N+1$ :
if $N+1$ is a prime power $p^a$, then there are exactly $2^{a-1}$ valid sequences, since you have to choose wether you pick $p^i$ or not for $0 \lt i \lt a$.
If $N+1$ has several prime divisors, I don't think there is a nice formula giving the number of valid collections from the multiset of exponents in the prime factorisation of $N+1$.


text:
Q: jQuery sortable serialize two columns in one database call? Hey all. A quick overview of what I'm trying to accomplish. I have two columns of data. Each column has an arbitrary amount of homogeneous elements.  On the jQuery sortable update event I want to serialize the location of all the elements in their respectable column. Each element in the columns has an id of the form item_{id}.  In the update event, I will serialize the elements in both columns.  I was wanting to know if there was an efficient way to serialize the col1 and col2 column orders and combine them into a single database call.  Out of the box, the sortable("serialize") method will return a formatted string like:
item[]=88&item[]=1&item[]=2&item[]=90

So, in the update event for column 1, I have:
$("#col1").sortable({
    handle: '.item h2',
    connectWith: '#col2',
    update: function(event, ui) { Update(event, ui); }
}).disableSelection();

And likewise for column 2:
$("#col2").sortable({
    handle: '.item h2',
    connectWith: '#col1',
    update: function(event, ui) { Update(event, ui); }
}).disableSelection();

And the Update event:
function Update(event, ui) {
    var col1Order = $("#col1").sortable("serialize");  // Returns item[]=88&item[]=1&item[]=2&item[]=90
    var col2Order = $("#col2").sortable("serialize");  // Returns item[]=23&item[]=10&item[]=65
}

Is there an efficient way to combine the column 1 ordering and column 2 ordering into one database call (It will store the updated position in the database)?
If I concatenate the two results together, it will result in a string of the form:
item[]=88&item[]=1&item[]=2&item[]=90&item[]=23&item[]=10&item[]=65

With this form, you are unable to differentiate which item came from which column.  I have pondered different approaches. One approach would format the query string to look something like ?col1=88_1_2_90&col2=23_10_65 and then on the server side splitting the col1 value, 88_1_2_90, on the '_' which would give me an array of values (88 in position 0, 1 in position 1, and so on) and split the col2 value using the same method, but I thought there might be a more elegant way to accomplish this.
My main goal is to avoid making two separate database calls (one for column1 and and another for column2).  I could serialize col1 and make a call to the database updating the positions of the elements within col1 and then serialize col2 and make another call to the database updating the positions of the elements within col2, but that's what I was trying to avoid.
I'm open to any and all suggestions.  Thanks in advance.

A: You can solve this problem using:
jQuery('.column').sortable('serialize', {key: 'widgets[0][]'});

A: What about using nested arrays? You should get something like this:
item[0][]=88&item[0][]=1&item[0][]=2&item[0][]=90&item[1][]=23&item[1][]=10&item[1][]=65

You can easily use array-related functions to flatten that into one array, if needed.


text:
Q: Blur image with pixastic and set it as background with jquery i have a problem that is bothering me form 2 days.
I'm developing a little music sharing site and i have a problem making the design for the player.
I want to apply a blurred image background to a div with CSS and with the blur begin applied on the image via JS all with pixastic js library. The problem is that pixastic gives me a HTMLImageElement witch i can't apply to a css with $('.footer').css('background', "url(" + img.toDataURL("image/png")+ ")" }); since toDataURL works only with canvas elements.
How can i do that?
My code so far is:
 var img = new Image();
    img.src = '<?php echo $hd ?>';
    img.onload = function() {
    Pixastic.process(img, "blurfast", {amount:1});
    }

    $('.footer').css('background', "url(" + img.toDataURL("image/png")+ ")" });

The $hd is a http url that points to an album artwork using lastfm API

A: I'm not sure about first argument of css method and why you dont use img.src as url of image? Try something like this:

$('.footer').css('background-image', 'url(' + img.src + ')');

Ok I found probably answer on documentation:
var options = {};
Pixastic.process(image, "action", options);
options.resultCanvas; // <- holds new canvas

So in your case it would be:
var img = new Image(),
    options = {};

options.amount = 1
img.src = '<?php echo $hd ?>';
img.onload = function() {
    Pixastic.process(img, "blurfast", options);
    $('.footer').css('background', "url(" + options.resultCanvas.toDataURL("image/png")+ ")" });
}


text:
Q: Как сделать отступ первого слова в абзаце TextView? android:layout_marginLeft="16dp"

Так сдвигается весь абзац, а мне нужно только первое слово сдвинуть. То есть мне нужно сделать "красную строку".
A: \t, в начале текста. Это управляющий символ, и при отображении строки он будет заменен 4мя пробелами. Наверняка вы сталкивались с \n - переходом на новую строку.


text:
Q: Matrices - Find matrix E Suppose $A = \begin{bmatrix}1&2&-1\\1&1&1\\1&-1&0\end{bmatrix}$ and $D = \begin{bmatrix}1&2&-1\\-3&-1&3\\2&1&-1\end{bmatrix}$. I need to find the matrix $E$ such that $EA = D$, if possible.
What I have tried is $E = D/A$. Would this yield the solution I am looking for as I'm not sure about how to solve this.

A: Multiply $EA=D$ with $A^{-1}$ on both sides, you get
$$EA(A^{-1})=D(A^{-1})$$
So $E=D(A^{-1})$


text:
Q: unable to install java using puppetlabs-java I am trying to install jdk-8u171-linux-x64.tar.gz using puppetlabs-java.below is my puppet code:
java::oracle { 'jdk8' :
    ensure  => 'present',
    version => '8',
    java_se => 'jdk',
    oracle_url => 'http://download.oracle.com/otn/java/jdk/',
    version_major => '8u171',
    version_minor => 'b11',
    url => 'http://download.oracle.com/otn-pub/java/jdk/8u171-b11/512cd62ec5174c3487ac17c61aaa89e8/jdk-8u171-linux-x64.tar.gz',
    url_hash => '512cd62ec5174c3487ac17c61aaa89e8',
}

error:'rpm --force -iv /tmp/jdk-8u171-linux-x64.rpm' returned 1 instead of one of [0]
error: ./jdk-8u171-linux-x64.rpm: not an rpm package (or package manifest):

A: When you try to access that URL for download, you get an unauthorized page.
This is your problem. You must accept oracle's agreement before files download, if you don't, you get this page...


text:
Q: One time salts and server password comparison I've read that one of the more secure ways to authenticate a user is to use one time salts when hashing the password. What I don't get is:
If the client generates a new salt every session, won't the resulting salt+password hash be different every session? If so, how will the server be able to compare the sent password with it's stored password? Is there a way for servers to compare different hashes and still be able to discern that the same password was used?
(Disclaimer: I'm not trying to reinvent the wheel/write a login protocol (I know, I know: use SSL/TLS). I'm just curious as to the high level functioning of login protocols)

A: you only generate a new salt when the user sets the password initially. Then you save the salt along with the password hash.

A: You only need to generate the salt only once and may every time the password been changed.
The client needs not to store the salt anywhere or even been aware of that. The salt will be stored by the server - along with the hash.
Its recommended that you store the hash and the salt in two different databases..


text:
Q: EclipseLink PreUpdate on OneToOne Relationship not persisted I have a PreUpdate method which gets executed, but when flushing the entityManager the changes on the dependent entity are not persisted.
Following is my minimal (non) working example:
Entities
@Entity
@Table(name = "HOUSE")
public class House {

    @Id
    @Column(name = "ID")
    private long id;

    @OneToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "INFO_ID")
    private HouseInfo info;

    @PreUpdate
    protected void komplettiereEingabeWerte() {
        info.setCode("TEST");
    }

    //getters and setters
}

@Entity
@Table(name = "HOUSE_INFO")
public class HouseInfo {

    @Id
    @Column(name = "ID")
    private long id;

    @Column(name = "CODE")
    private String code;

    //getters and setters
}

Testcase
@Test
@Transactional(TransactionMode.ROLLBACK)
public void testPreUpdate() {
    House house = entityManager.find(House.class, 1L);
    house.setInfo(new HouseInfo());
    entityManager.flush();
    entityManager.clear();

    house = entityManager.find(House.class, 1L);
    assertEquals("TEST", house.getInfo().getCode());
}

The Test fails due to an AssertionError on the last line as Code is null.
I am using EclipseLink version 2.7.4 with an Oracle DB (the same behaviour was also observed with an in memory Derby DB) and the Test is running with UnitilsJUnit4 in a SpringApplicationContext.
How can I fix this problem? Thank you.

A: The JPA Spec states that:

In general, the lifecycle method of a portable application should not invoke EntityManager or query operations, access other entity instances, or modify relationships within the
  same persistence context. A lifecycle callback method may modify the non-relationship
  state of the entity on which it is invoked

The simple answer is, then, that entity listeners cannot be used for the task. Implement the relevant logic in your service layer instead.


text:
Q: python requests post method results inconsistent Problem:
Response when using python requests and chrome's postman are not consistent for the same request.
things to note:
1) url is on https.
2) json is the data format for both request and response
3) python version 3.x
4) requests version 2.2
python code:
headers = {'Content-Type': 'application/json'}
response = requests.post(self.__url, data=jsonpickle.encode(apiContractObject), headers=headers, verify=True)
print(response.text)

response in python code
{
  "productId": 0,
  "productName": "testingPy",
  "yearsArray": [
    {
      "key": 0,
      "value": {
        "outgo": 100.0,
        "benefit": 0.0,
        "net": -100.0,
        "year": "2017-2018",
        "age": 0
      }
    }
  ]
}

response in postman for same request
{
  "productId": 0,
  "productName": "testingPy",
  "yearsArray": [
    {
      "key": 0,
      "value": {
        "outgo": 100,
        "benefit": 0,
        "net": -100,
        "year": "2017-2018",
        "age": 0
      }
    },
    {
      "key": 1,
      "value": {
        "outgo": 0,
        "benefit": 110.39,
        "net": 110.39,
        "year": "2018-2019",
        "age": 1
      }
    }
  ]
}

the difference
The yearsArray has 1 element in python code's response but actually should have 2 as seen in the postman response
I'm a newbie to Python!
EDIT:
the apiContractObject is this python class:
class FDCashflowContract:
    """Contract object for API"""
    def __init__(self):
        self.projectionType = 0
        self.isCumulative = 0
        self.dateOfDeposit = ''
        self.depositHolderDob = ''
        self.depositDuration = DepositDuration(0, 0, 0)
        self.depositAmount = 0
        self.compoundingFrequency = 0
        self.interestPayOutFrequency = 0
        self.interestRate = 0,
        self.doYouKnowMaturityAmount = True
        self.maturityAmount = 0
        self.doYouKnowInterestPayOutAmount = True
        self.interestPayOutAmount = 0
        self.firstInterestPayOutDate = ''
        self.productName = 'testingPy'

    class DepositDuration:
        """A class that represents the duration object for use as a contract object"""
        def __init__(self, years, months, days):
            self._years = years
            self._months = months
            self._days = days

but the instance that is passed is this:
duration = finfloApiModel.DepositDuration(1, 0, 0)

contract = finfloApiModel.FDCashflowContract()
contract.depositAmount = 100
contract.depositDuration = duration
contract.interestRate = 10
contract.dateOfDeposit = '05-12-2017'
contract.depositHolderDob = '04-27-2017'
contract.isCumulative = 1
contract.projectionType = 1

this is postman request:
{
  "productId": 0,
  "projectionType": 1,
  "productName": "testingPy",
  "isCumulative": 1,
  "dateOfDeposit": "2017-05-12T06:26:45.239Z",
  "depositHolderDob": "2017-05-12T06:26:45.239Z",
  "depositDuration": {
    "years": 1,
    "months": 0,
    "days": 0
  },
  "depositAmount": 100,
  "compoundingFrequency": 0,
  "interestPayOutFrequency": 0,
  "interestRate": 10,
  "doYouKnowMaturityAmount": false,
  "maturityAmount": 0,
  "doYouKnowInterestPayOutAmount": false,
  "interestPayOutAmount": 0
}

A: Fundamentally: The problem as @Ray & @mohammed suggested was the request. The REST service is written on ASP.NET Web API 2 platform and the model binder on the REST controller expects the request object (JSON) to be exactly of the same structure and spelling as the model that is expected to it as input.
Problem identified: The problem in the Python request was that the DepositDuration object's attributes Years, Months and Days were preceded with _ and weren't binding and defaulting to zeroes on the api which was rightly responding with an appropriate response.
class DepositDuration:
        """A class that represents the duration object for use as a contract object"""
        def __init__(self, years, months, days):
            self._years = years
            self._months = months
            self._days = days

Solution: I've removed the _ from the python class DepositDuration's attributes years, months and days and voila everything works!
class DepositDuration:
        """A class that represents the duration object for use as a contract object"""
        def __init__(self, years, months, days):
            self.years = years
            self.months = months
            self.days = days


text:
Q: call onClick on a button on a different layout I'm working on a application where I have a list view. The list view has a button which is on different layout file. How can I call the button from my activity? I've tried adding that xml file to my activity but the setOnClickListener doesn't seems to work.
This is how my xml file looks like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:orientation="horizontal"
    android:padding="20dp">

    <EditText
        android:id="@+id/objectiveOtherAddedEditText"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_marginLeft="28dp"
        android:ems="10" />

    <ImageButton
        android:id="@+id/addOtherObjectiveTextBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:background="@drawable/round_button"
        android:src="@android:drawable/ic_input_add"/>

</LinearLayout>

and this is where I want to call it:
public class VisitObjectiveFragment extends Fragment {

public static final String TITLE = "Visit Objective";
SQLiteDatabase database;
SQLiteOpenHelper dbHelper;

public static VisitObjectiveFragment newInstance() {

    return new VisitObjectiveFragment();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_visit_objective, container, false);
    final View view1 = inflater.inflate(R.layout.other_objective_list_view, container, false);

    ListView listView = (ListView) view.findViewById(R.id.listview_objective);
    ImageButton buttonAdd = (ImageButton) view1.findViewById(R.id.addOtherObjectiveTextBox);

    buttonAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}

}

A: you can use the <include></include> tag to specify the xml inside your parent xml

A: Put setOnClickListener(new View.OnClickListener() {} inside your adapter class. If you don`t have one. Create it

A: you should add inflated object to your main view
public class VisitObjectiveFragment extends Fragment {

public static final String TITLE = "Visit Objective";
SQLiteDatabase database;
SQLiteOpenHelper dbHelper;

public static VisitObjectiveFragment newInstance() {

    return new VisitObjectiveFragment();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_visit_objective, container, false);
    final View view1 = getActivity().getLayoutInflater().inflate(R.layout.other_objective_list_view, null);

    ListView listView = (ListView) view.findViewById(R.id.listview_objective);
    ImageButton buttonAdd = (ImageButton) view1.findViewById(R.id.addNewOtherObjectiveTextBox);

    view.addView(buttonAdd);

    buttonAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}

A: All you need is create callback interface. See the official documentation (link below) https://developer.android.com/training/basics/fragments/communicating.html
It allow you to communicate between fragment-activity.