text:
Q: Fortify throws error while scanning Visual Studio project I'm trying to run Fortify on a Visual Studio 2008 project. The project builds successfully on its own. When I try to analyze the project with Fortify using the Visual Studio integrated controls, the project builds successfully but an error message is thrown. Here's the output from Fortify console:
Fortify SCA...
Running: "-show-runtime-properties"
Running: "-b" "ProjectName" "-clean"
Error setting VCProject Path. Abort VC project related scan
Scan Failed Could not load file or assembly 'Microsoft.VisualStudio.VCProjectEngine, Version=8.0.0.0, Culture=neutral, PublicKeyToken=<string here>' or one of its dependencies. The system cannot find the file specified.
   at FortifyBase.Scanner.CPPScanUtil.ResetVCProjectExecutableDirectories()
   at FortifyCommon.Scanner.BuildListeners.VSBuildDone(vsBuildScope scope, vsBuildAction action)
Scan Failed:
Could not load file or assembly 'Microsoft.VisualStudio.VCProjectEngine, Version=8.0.0.0, Culture=neutral, PublicKeyToken=<string here>' or one of its dependencies. The system cannot find the file specified.

When I run Fortify from the standalone Audit Workbench, I get the following error message:
SCA Commandline invocation failed
[error]: Build ID "ProjectName" doesn't exist.

I keep most of the default scan options except changing 'Is this a J2EE web application' to 'No' (I also tried leaving this to 'yes' but that didn't work either.
Searching for any info on the error messages only produced another question on Stack Overflow but the project setup seems quite different from my Visual Studio project. Anyways, I also tried running the scan from command line with the arguments provided by Visual Studio but I get the same error message.
Fortify documentation mentions that the build ID is used to track which files are compiled and linked as part of a build and later to scan those files and that it is usually the project name. I tried a few different strings as the build ID but nothing seems to work.
Anyone has any idea where I'm going wrong? Thanks in advance.
Update: The problem occurs during the translate phase of the analysis due to which the build ID is not created at all. Here's the log from the sourceanalyzer log:
[2010-08-23 21:20:53 INFO]
Fortify Source Code Analyzer 5.1.0.0061
[2010-08-23 21:20:53 INFO]
Args:
["-b", "ProjectName", "-machine-output", "-vsversion", "8.0", "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe", "ProjectName.sln", "/rebuild", "DEBUG"]
[2010-08-23 21:20:53 INFO]
VM Args:
"-XX:SoftRefLRUPolicyMSPerMB=100 -Xss1M -Xmx600M -Xms16M"
[2010-08-23 21:21:04 INFO 1102]
Compiler execution failed (exit code: 1).
[2010-08-23 21:21:04 WARNING]
exit(1)

A: OK, I think this is a known issue with C/C++ translation on VS2010.  The workaround I found is:

*

*Open a Visual Studio x86 Command Prompt

*Change to the KindleExport.sln's directory

*Run:
sourceanalyzer -b kindleexport devenv KindleExport.sln /REBUILD

*Run:
sourceanalyzer -b kindleexport -scan -f KindleExport.fpr


text:
Q: DropBox authenticate in cordova / phonegap (android) Im trying to add dropbox support in my phonegap app, but i can't authenticate. (via dropbox-js/https://github.com/dropbox/dropbox-js)
I use:
client.authDriver(new Dropbox.Drivers.Cordova({rememberUser:true}));

The app opens a login/confirmation-dialog/ok but locks in the last step
in browser works fine with:
client.authDriver(new Dropbox.Drivers.Redirect({rememberUser:true}));

Is there any solution compiling with adobe phonegap build?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: Attempt to use ZIP archive that was already closed I want to open a zip file A001-C-002.zip. Its raising Attempt to use ZIP archive that was already closed error.
from pathlib import Path
import pandas as pd
import zipfile
import os
import sys

path = "./CODEX/input/"

for filename in os.listdir(os.getcwd()):
    with open(os.path.join(os.getcwd(), filename), 'r') as f:
        # Antibody information
        ab = pd.read_excel("HUBMAP B004 codex antibodies metadata.xlsx")
        print(f"Antibody metadata column names:\n {ab.columns.values}")

        # Patient A001
        with zipfile.ZipFile("A001-C-002.zip") as z:
            for filename in z.namelist():
                if not os.path.isdir(filename):
                    for line in z.open(filename):
                        print(line)
                    z.close()

Traceback:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_4872/558093962.py in <module>
      9             for filename in z.namelist():
     10                 if not os.path.isdir(filename):
---> 11                     for line in z.open(filename):
     12                         print(line)
     13                     z.close()

/usr/lib/python3.8/zipfile.py in open(self, name, mode, pwd, force_zip64)
   1499             raise ValueError("pwd is only supported for reading files")
   1500         if not self.fp:
-> 1501             raise ValueError(
   1502                 "Attempt to use ZIP archive that was already closed")
   1503

ValueError: Attempt to use ZIP archive that was already closed

A: Your trouble comes from the last three lines of your code:
                for line in z.open(filename):
                    print(line)
                z.close()

It looks like you want the z.close call to be closing the file you opened in the first of these lines. But that's not what it does. z is the whole zip archive you've been scanning, and when you close it, you won't be able to open any of the files it contains again (not without reopening the whole thing anyway).
I suspect you want something more like this:
with z.open(filename) as file:
    for line in file:
        print(line)

Here we use a with statement to handle the closing of the inner file within the archive, which remains open throughout (until the outer with statement ends). I give a name to that file object, file so that the with statement can hand it off to the for loop.


text:
Q: node.js request post retrieve last id from db.json After posting in db.json a new record (transaction with several data), I would like to get the id of the new record before going on. How-to do it ? I am stuck
I have in my db.json a "table" positions with an id automatically generated
my request is
request({
    url: url + '/api/positions,
    method: 'POST',
    form: transaction
}, ????);

I want in my callback retrieve position.id (as I have to use it in another part of code).
Thanks a lot
Olivier

A: Make sure your API is giving back the position id, Im assuming you're using express, so in /api/positions have the response be res.send({position...});
EDIT, So you're asking about routing? Here is an awesome guide: https://expressjs.com/en/guide/routing.html but Ill give you an example of what I mean.
app.post('/api/positions', function(req, res) {
  //your logic goes here, so you are sending a 'transaction' object
  // npm install and use body parser so you can retrieve attributes
  // from the body of the post
  res.send({position: x})
})

A: Maybe some thing like that.
...
var router = jsonServer.router('db.json');
...

// 'router.db.get' will fetch any first level attribute from your db.json
var positions = router.db.get('positions').value();
var lastPosition = positions[positions.length-1];


text:
Q: How to add a new buffer to opening nvim-qt instead of opening a new instance on Windows? I have set up nvim-qt version 06 on my Windows 10 to use it instead of notepad++.
And when I double-click on a file, a new nvim-qt instance will open.
But now, what I want is if I double-click on a file, nvim-qt will open a new buffer in running nvim-qt instead of opening a new nvim-qt instance. It will save me a lot of time.
Do you know any way to do that? please help
Thanks,


text:
Q: ajuda em capturar várias strings e armazena-los em uma array String names = "<input type="radio" name="pergunta23g" value="SIM"/> Qual? <input type="text" name="pergunta23gQual" class="dados"> Onde<input type="text" name="pergunta23gOnde" class="dados">	"

gostaria de guardar esses três valores:
gostaria de pegar só os names sem as aspas nessa string.
como eu faço o tratamento?
armazenar em uma array de string como pergunta23g, pergunta23gQual, e pergunta23gOnde.

A: String names = "<input type=\"radio\" name=\"pergunta23g\" value=\"SIM\"/> Qual? <input type=\"text\" name=\"pergunta23gQual\" class=\"dados\"> Onde<input type=\"text\" name=\"pergunta23gOnde\" class=\"dados\">	";
String[] inputs = names.split("input");
Pattern pattern = Pattern.compile("name=\"(.*?)\"");

List<String> valores = new ArrayList();
for (String input : inputs) {
    Matcher matcher = pattern.matcher(input);

    if (matcher.find())
    {
        valores.add(matcher.group(1));
    }
}

for (String valor : valores) {
    System.out.println(valor);
}

Saída

pergunta23g
pergunta23gQual
pergunta23gOnde

Explicações:

*

*Adicionei a \ nos "

*Utilizei a class Pattern

*name=\"(.*?)\" vai pegar só o que tiver dentro das " após o name=

*Fiz split em um Array para utilizar o matcher em cada input

*Adicionei numa nova lista os valores corretos


text:
Q: Retrieving a Many-t-Many Field value with django-rest-framework serializers I want to retrieve manytomany field value in my serializer.
My Project Model is as
 class Project(models.Model):
    title = models.CharField(max_length=200,blank=True)
    detail = models.CharField(max_length=200,blank=True)
    addedby = models.ForeignKey(User,on_delete=models.CASCADE,related_name='projectadder')
    date = models.DateTimeField(auto_now_add=True)
    projecttype = models.ForeignKey(ProjectType,on_delete=models.CASCADE,related_name='projecttpye')
    cost = models.CharField(max_length=20,blank=True)
    pros = models.CharField(max_length=500,blank=True)
    cons = models.CharField(max_length=500,blank=True)
    team = models.ManyToManyField(User)
    supervisor = models.ManyToManyField(Supervisor)
    cosupervisor = models.ManyToManyField(CoSupervisor)
    technology = models.ManyToManyField(Technology)
    tags = models.ManyToManyField(Tag)
    teamleader = models.ForeignKey(User,on_delete=models.CASCADE,related_name='teamleader')
    proposal = models.CharField(max_length=500,blank=True)
    buyers = models.ManyToManyField(Buyer)
    reviews = models.ManyToManyField(Review)
    requirements = models.ManyToManyField(ProjectRequirement)
    images = models.ManyToManyField(ProjectImage)

My serializer is as:
class ProjectSerializer(serializers.ModelSerializer):
    projecttype = serializers.ReadOnlyField(source='projecttype.name')
    addedby = serializers.ReadOnlyField(source='addedby.username')
    teamleader = serializers.ReadOnlyField(source='teamleader.username')
    # team = serializers.ReadOnlyField(source='team')
    class Meta:
        model= Project
        fields = '__all__'

It is retrieving ForiegnKey elements sucessfuly but not retriving ManytoMany Field Values?

A: I think you need to set the serializers for those ManyToManyFields.
For example, the model has a many to many relationship with the Supervisor model.
So you can set the supervisors field in the ProjectSerializer.
class ProjectSerializer(serializers.ModelSerializer):
    ...

    supervisors = SupervisorSerializer(many = True, read_only = True, fields=(...))

    class Meta:
        model= Project
        fields = (..., 'supervisors',)

In order to set fields parameters, you can customize __init__ function.
class SupervisorSerializer(serializers.ModelSerializer):
    ...

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        set_fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        if set_fields is not None:
            allowed = set(set_fields )
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

You need to add the serializers for all the many to many fields.
Hope it could help.


text:
Q: Can I make Steam give me a description or screenshots of a game when browsing my library? When I click a game in my library that I've never played, the right side of the window presents a lot of info I don't want and virtually none of the info that I do. Is there some way to change this behavior?

A: The Library page for a game is generally geared towards people who already own that game, which is why it contains things like news, achievements, etc. And unfortunately, no, it's not customizable.
There is, however, a page in Steam for every game that gives a description, shows Screenshot, etc. The game's Store Page. And the library page should generally always contain a 'Store Page' link. It's not quite what you wanted, but it's AFAIK as close to what you asked for as Steam has.

A: If I understood your problem correctly, you have 2 solutions

*

*First display only installed games. See screenshot below (In red on the left)

*Second : Change the layout of the Library. See screenshot below (In red on the right)


text:
Q: CKAN page slows down when tracking is enabled CKAN is running on version 2.9.1. When enabled ckan's native tracking, it is slowing down the page load. On the first hit it loads quickly but on the next hit, it takes about 90 seconds.
There is a reverse proxy Nginx. On it, I'm getting timeout error on the _tracking call.

*99 upstream timed out (110: Connection timed out) while reading response header from upstream,

But on the application level, I had put in some print statements which are all getting printed(the call is reaching the CKAN application).

A: Nginx was expecting a response from the application, but it wasn't responding. I've set the timeout for this at Nginx manually. Now there is no lag.


text: Q: Is there a django function to pass a object in database to the next redirected page in views in django I'm developing a project in Django in which I'm using a view(verify) to verify the student's login details. If the student is valid user then it'll redirect to a page(display.html) where all the details of that particular student is displayed. How can i pass the object containing the student details from verify view to the display.html??


text:
Q: Remove Dynamically Added Controls from Userform I have an Excel userform with dynamically added checkboxes.
I add the checkboxes with code that looks like this:
Set chkBox = Me.Controls.Add("Forms.Checkbox.1", "Checkbox" & i)

I want to remove all of these checkboxes.
Dim j As Integer
'Remove all dynamically updated checkboxes
For Each cont In Me.Controls
    For j = 1 To NumControls
        If cont.Name = "Checkbox" & j Then
            Me.Controls.Remove ("Checkbox" & j)
        End If
    Next j
Next cont

I get the following error message:

A: Assuming there are no othe control names starting with "Checkbox",
For Each cont In Me.Controls
    If InStr(cont.Name, "Checkbox") = 1 Then
        Me.Controls.Remove cont.Name
    End If
Next cont

A: if you already know the name of the controls, the type, and how many, why double loop ?
note that ONLY controls created at runtime can be removed.
'the following removes all controls created at runtime
Dim i As Long
On Error Resume Next
With Me.Controls
    For i = .Count - 1 to 0 step -1
        .Remove i
    Next i
End With
Err.Clear: On Error GoTo 0

and for your case : 'if all naming are correct
Dim j&
For j = 1 To NumControls
    Me.Controls.Remove "Checkbox" & j
Next j

A: A better approach may be to keep track of the controls you create (eg in a collection), and use that to remove them.
This way your code is not bound to the name format, and can be applied to other control types too.
Private cbxs As Collection

Private Sub UserForm_Initialize()
    Set cbxs = New Collection
End Sub

' Remove all dynamicly added Controls
Private Sub btnRemove_Click()
    Dim i As Long
    Do While cbxs.Count > 0
        Me.Controls.Remove cbxs.Item(1).Name
        cbxs.Remove 1
    Loop
End Sub

' Add some Controls, example for testing purposes
Private Sub btnAdd_Click()
    Dim i As Long
    Dim chkBox As Control
    For i = 1 To 10
        Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "SomeRandomName" & i)
        chkBox.Top = 40 + i * 20
        chkBox.Left = 20
        cbxs.Add chkBox, chkBox.Name  '- populate tracking collection
    Next

    ' Demo that it works for other control types
    For i = 1 To 10
        Set chkBox = Me.Controls.Add("Forms.ListBox.1", "SomeOtherRandomName" & i)
        chkBox.Top = 40 + i * 20
        chkBox.Left = 60
        cbxs.Add chkBox, chkBox.Name
    Next

End Sub

A: Adding a check for the control seemed to fix this. Not entirely sure why, but it works.
   Dim j As Integer
'Remove all dynamically updated checkboxes
For Each cont In Me.Controls
    If TypeName(cont) = "CheckBox" Then
        For j = 1 To NumControls
            If cont.Name = "Checkbox" & j Then
                Me.Controls.Remove cont.Name
                Exit For
            End If
        Next j
    End If
Next cont

A: I rewrote the original code using command buttons, and just added "Me.Controls.Count" rather than "NumControls" and defined "Cont" as a Control. It seems to be working for me. Please let me know if this works for you:
-->
On Error Resume Next
Dim Cont As Control
Dim C As Integer
'Remove all dynamically updated checkboxes
For Each Cont In Me.Controls
    For C = 1 To Me.Controls.Count
    If Cont.Name = "CommandButton" & C Then
        Me.Controls.Remove ("CommandButton" & C)
    End If
    Next C
Next Cont

A: Another way to select which controls are kept and which are deleted is to use the .Tag attribute.
This allows some fine control of the controls as they are added, for example by using the .Tag as a bitfield.
At creation time:
With Me.Controls.add("Forms.Label.1", Visible:=True)
{code}
    .Tag = 1
{more code}

Then when the time comes to tidy up:
For Each C In Me.Controls
    If C.Tag = 1 Then Me.Controls.Remove C.Name
Next


text:
Q: Code to form a set from a list of element pairs in java Say I have a list of pair of elements like (1, 2) (3, 4) where no duplicates are present and for a pair (p, q) p != q.
How to form a set from this elements using simple code (I do not intend to use a data structure like disjoint set and unions but java library APIs - unless the code can be written in a simple fashion).
Example: (1, 2) (2, 4) (5, 6) (4, 7) (3, 5) should output:
{1, 2, 4, 7} and {3, 5, 6}
    List<Set<Integer>> list = new ArrayList<>();
    for(String s : pairs){
        String[] values = s.split(" ");
        Integer val1 = Integer.parseInt(values[0]);
        Integer val2 = Integer.parseInt(values[1]);

        Set<Integer> pairSet = new HashSet<>();
        pairSet.add(val1);
        pairSet.add(val2);

        boolean exists = false;
        for(Set<Integer> set : list){
            if(set.contains(val1) || set.contains(val2)) {
                set.addAll(pairSet);
                exists = true;
                break;
            }
        }
        if(!exists)
            list.add(pairSet);
    }

This is a naive approach which is incorrect. If I get a sequence (1 2) (3 4) and (2 3) then the output becomes {1, 2, 3} and {3, 4}.
This happens because the list of sets gets created like this:
{1, 2} and then {3, 4} then when the pair (2 3) comes, it DOES NOT merge the 2 sets.
I can write a code to check the first value is present in any set say S1 and then same for the other value say S2 and then merge:
    //loop -> s1 = find val1
    //loop -> s2 = find val2
    if s1 != null and s2 != null //merge s1 and s2
    if(s1 == null && s2 != null) //add val1 and val2 to s2
    if(s1 != null && s2 == null) //add val1 and val2 to s1
    if(both null) create a new set of val1 and val2

Too many loops and conditions. Any simpler solution?

A: Revised version:
Here, I have made it using what you referred to as Naive approach:
public static List<Set<Integer>> answer(String[] pairs){

    List<Set<Integer>> list = new LinkedList<>();
    // For each pair, separate the numbers
    //Initialize with initial set
    Set<Integer> init = new HashSet<>();
    String[] splitted = pairs[0].split(" ");
    init.add(Integer.parseInt(splitted[0]));
    init.add(Integer.parseInt(splitted[1]));

    list.add(init);

    // To be used to maintain set record ahead
    List<Set<Integer>> setsRecord = new LinkedList<>();

    boolean found = false;
    Integer i1, i2;
    for(String s : pairs){
        i1 = Integer.parseInt((splitted = s.split(" "))[0]);
        i2 = i2 = Integer.parseInt(splitted[1]);
        for(Set<Integer> set : list){
            if(set.contains(i1) || set.contains(i2)){
                // If element has already been found in a set, create a common set
                if(setsRecord.size() >= 1){
                    setsRecord.get(0).addAll(set);
                    // And remove this set
                    list.remove(set);
                }
                else{
                    set.add(i1);
                    set.add(i2);
                    // Maintain a record of this set
                    setsRecord.add(set);
                }
                found = true;
            }
        }
        // Empty the temporary set record
        setsRecord.clear();

        if(!found){
            Set<Integer> newSet = new HashSet<Integer>();
            newSet.add(i1);
            newSet.add(i2);
            list.add(newSet);
        }
        found = false;
    }
    return list;
}

Demo.

A: I am posting a solution. If someone can make this code simpler it would be great. TIA
        static void formSet(String[] pairs) {

    List<Set<Integer>> list = new ArrayList<>();
    for(String s : pairs){
        String[] values = s.split(" ");
        Integer val1 = Integer.parseInt(values[0]);
        Integer val2 = Integer.parseInt(values[1]);

        Set<Integer> pairSet = new HashSet<>();
        pairSet.add(val1);
        pairSet.add(val2);

        Set<Integer> val1_set = null, val2_set = null;
        for(Set<Integer> set : list){
            if(set.contains(val1)) {
                val1_set = set;
            }

            if(set.contains(val2)) {
                val2_set = set;
            }
        }
        if(val1_set == null && val2_set == null)
            list.add(pairSet);
        if(val1_set != null && val2_set == null)
            val1_set.addAll(pairSet);
        if(val1_set == null && val2_set != null)
            val2_set.addAll(pairSet);
        if(val1_set != null && val2_set != null){
            list.remove(val2_set);
            val1_set.addAll(val2_set);
        }
    }

    for(Set<Integer> set : list){
        System.out.println(set);
    }
}

here's a link to codereview:
https://codereview.stackexchange.com/questions/163301/forming-a-set-from-a-pair-of-numbers

A: A simple DFS would do the trick if you consider each pair as a description of an edge of a graph.
import java.util.*;
import java.lang.*;
import java.io.*;

class Solution
{
  static int n = 1000000;
  static ArrayList< ArrayList<Integer> > adj = new ArrayList<ArrayList<Integer>>();
  static Boolean[] visited = new Boolean[n];

public static void main (String[] args) throws java.lang.Exception
{
    String input[] = {"1 2", "3 4", "2 3","5 6"};
    System.out.println(answer(input));
}

public static void dfs(int u,Set<Integer> res){
    visited[u] = true;
    for(int e : adj.get(u)){
        if(!visited[e])
             dfs(e,res);
    }
    res.add(u);
}
static void init(){
    for(int i = 0 ; i < n ; i++)
        adj.add(new ArrayList<Integer>());
}

public static List<Set<Integer>> answer(String[] pairs){
    init();
    List<Set<Integer>> list = new LinkedList<>();
    Set<Integer> elements = new HashSet<Integer>();
    for(int i = 0 ; i < pairs.length ; i++){
    String[] splitted = pairs[i].split(" ");
     int u = Integer.parseInt(splitted[0]);
     int v = Integer.parseInt(splitted[1]);
        adj.get(u).add(v);
        adj.get(v).add(u);
        visited[u] = visited[v] = false;
        elements.add(u);elements.add(v);
    }

    for(int e : elements){
        if(!visited[e]){
            Set<Integer> tmp = new HashSet<Integer>();
            dfs(e,tmp);
            list.add(tmp);
        }
    }
    return list;
}
}


text:
Q: getResource() can't load content in a jar I can successfully load resources that stand in some package of my src/ dir in eclipse. Now, I export the jar (right click src, export, jar, and keep default settings) and can't have the resource loaded in another eclipse project.
I build the path to the resource by indicating a class standing in the same package name:
URL out = getClass().getClassLoader().getResource(packageName(getClass())+"file.glsl");
// out is null when loaded from a jar!!

protected static String packageName(Class<?> clazz){
    return packageName(clazz.getPackage());
}
protected static String packageName(Package p){
    return c + p.getName().replace('.', c) + c;
}
protected static char c = File.separatorChar;

Do you see any wrong way?
I tried:

*

*getClass().getResource()

*getClass().getClassLoader().getResource()

*getClass().getClassLoader().getResourceAsStream()

*Thread.currentThread().getContextClassLoader().getResource()

*adding/removing the '/' char at the begining of the package name

*using either '/', '\', or File.separatorChar, and even '.', all failed.

I verified that:

*

*jar contains the resource (expanding the jar content in eclipse project's "Referenced Libraries")

*packageName(getClass())+filename) returns a clean name: "\org\jzy3d\plot3d\rendering\ddp\algorithms\dual_peeling_init_vertex.glsl"

I endlessly retrieve a null :/

EDIT: screenshot and code to show that "that should work"

You can retrieve this a SSCCE zipped eclipse project here
A user class
public class User {
    public static void main(String[] args) {
        Loader pair = new Loader(SomeClass.class, "shade_vertex.glsl");
        System.out.println("found:" + pair.getURL());

    }
}

Providing class dynamically with new SomeClass().getClass() produce the same result.
The loader
package com.pkg.loader;

import java.io.File;
import java.net.URL;

public class Loader {
    public Loader(Class<?> c, String file) {
        this(packageName(c.getPackage()), file);
    }

    public Loader(Package p, String file) {
        this(packageName(p), file);
    }

    protected Loader(String pack, String file) {
        this.pack = pack;
        this.file = file;
    }

    public String getStringPath() {
        return pack+file;
    }

    public URL getURL() {
        URL out = Thread.currentThread().getContextClassLoader().getResource(getStringPath());
        if(out==null)
            throw new RuntimeException("unable to find shader URL for :'"+getStringPath()+"'");
        return out;
    }

    protected static String packageName(Class<?> clazz){
        return packageName(clazz.getPackage());
    }

    protected static String packageName(Package p){
        return c + p.getName().replace('.', c) + c;
    }

    protected static char c = File.separatorChar;

    protected String pack;
    protected String file;
}

The marker class
public class SomeClass {}

A: First, try not to place source files directly in the default package (src).
Create at least one package to wrap your source because when jars are exported, the src folder isn't included. So if you create your own default package, then you'll have some defined root directory to base your resource paths on.
After you've created your own default package, your problem might already be fixed, but if it wasn't then try this:
YourClass.class.getResource("/your_root_package/blah/blah/file.glsl");

It works for me for images:
public static Image ICON32 = Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource("/files/images/icon32.png"));

Yeah, so, hope this helps. :)

A: The problem is actually this line:
protected static char c = File.separatorChar;

This will be a backslash on Windows, but paths for Class#getResource() must be forward slashes in order to work correctly. The JRE is probably looking for your path as a relative path and interpreting the backslash literally.
In any case, what you should be using for this particular example is:
URL out = getClass().getResource("file.glsl");

Class#getResource() already handles resolving this relative to the class, so it doesn't make sense to duplicate that code in your app.


text:
Q: Smooth Path traversing in C# I'm looking for a C# implementation of a Spline,
not to draw it, but to traverse it.
Basically I have a 2D game and I want an object to move on a predefined path.

Any ideas how to implement this ?
Thanks,
SW

A: Have a look at some equations on how to interpolate splines:
http://en.wikipedia.org/wiki/Spline_interpolation
This may also help: Calculate a bezier spline to get from point to point

A: When I had to do this for a game years ago, I implemented a form of parametric spline curve that was simple to build and required little in the way of CPU resources.  What I built is similar to what's in the linked article.  One really nice thing about this type of spline is that the math is not at all advanced.
Unfortunately, I don't have access to the C source code for my implementation.

A: Also check out Numerical Recipes, and netlib.org.


text:
Q: Uploading large .bak file to Azure Blob through Powershell So I am trying to create a powershell script which will upload a large (> 4GB) .Bak file to Azure Blob Storage but currently it is getting hung. This script works with small files which I have been using to test.
Originally the issue I was having was the requirement to have a Content-Length specified (I imagine due its size) so I now calculate the file size of the .bak file (as it varies slightly each week) and pass this through as a request header
I am a total powershell newbie, as well as being very new to Azure blob. (NOTE: I am trying to do this purely in powershell, without relying on other tools such as AzCopy)
Below is my script
Powershell Script
Any help would be greatly appreciated..

A: There are a few things to check. Since file is big, are you sure it isn't uploading? Have you checked network activity in performance tab of task explorer? AzCopy seems like a good option too that you can use from within Powershell, but if it's not an option in your case, then why not to use native AZ module for Powershell?
I suggest you using Set-AzStorageBlobContent cmdlet to see if it helps. You can find examples at Microsoft docs


text:
Q: Menu navigaton responsive (no Bootstrap) I'm trying to make this menu responsive, in particular I want it to appear like this : ☰  --> and when I click on it shows the links.
(The blue button, also I want it to appear as a normal link, like the other links)
I don't want to use Bootstrap, I want to use JavaScript And CSS.
HTML  CODE :

<link rel="stylesheet" type="text/css" href="./css/style.css" />

        Home
        Home
        Home

        Button

CSS CODE :
 * {
 margin: 0px;
 padding: 0px;
 font-family: Arial, Helvetica, Sans-serif;
 font-size: 12px;
 }
body a, body a:hover {
text-decoration: none;
}
.navigation-main {
background-color: #1f2124;
height : 59px;
border-bottom : 0px;
padding-left: auto;
padding-right: auto;
width: 100%;
}
#wrapper {
margin-left : auto;
margin-right : auto;
width : 100%;
padding-top : 0px;
padding-bottom : 0px;
}
.logo {
width : 125px;
position: relative;
top: 10px;
margin-left: 20px;
}
.logo img {
width : 38px;
height : 38px;
}
#menu a {
color: #FFFFFF;
text-decoration: none;
font-size: 14px;
padding-top: 19px;
padding-bottom: 22px;
position: relative;
left: 70px;
bottom: 20px;
padding-left: 10px;
padding-right: 10px;
}
#menu2 a {
color: #FFFFFF;
text-decoration: none;
font-size: 14px;
padding-top: 19px;
padding-bottom: 22px;
position: relative;
left: 1200px;
bottom: 50px;
}
.menu2 {
float: right;
}
#menu a:hover {
background-color: #2c97de;
}
.button-small {
height: 35px;
line-height: 31px;
font-size: 13px;
}
.button-round {
border-radius: 38px;
}
.button-prim {
background-color: #2c97de;
}
.button {
display: inline-block;
position: relative;
text-transform: uppercase;
font-size: 15px;
padding: 0 20px;
border-radius: 38px;
color: #fff;
outline: none;
border: 2px solid transparent;
text-shadow: 0 1px 1px rgba(0,0,0,.2);
bottom: 48px;
height: 30px;
line-height: 30px;
margin-right: 20px;
}

A: you can use this for our project.
jsFiddle
JS:
$(document).ready(function () {
    function CloseNav() {
        $(".navbar-collapse").stop().animate({'height': 0},300, function () {
            $('.navbar-collapse').removeClass('in').addClass("collapse");
        });
        $(".navbar-toggle").stop().removeClass('collapsed');
    }

    $('html').click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
        if (_opened === true && !clickover.hasClass("navbar-toggle")) {
            CloseNav();
        }

    });
});

HTML

      <button type="button" class="navbar-toggle"data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>
      Project name

Link

Link

Link

          Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default

Static top

Fixed top

CSS:
.wrapper {width:100%, height:100%;}

GL :-)


text:
Q: Getting Values From a Variable Returned From PHP I have the following variable returned from php to JavaScript: [{"id":"34"}, {"id":"35"}, ...]. I would like, the value of "id". How do I do that using JSON?

A: Try this:
var obj = [{"id":"34"}, {"id":"35"}];
console.log(obj[0]['id']);

Note: To make it dynamic use JS loop
Working fiddle


text:
Q: How can I bind a variable to an unused AVR I/O register using avr-gcc? I would like to bind a global variable to an unused I/O register (e.g. PORTB) using avr-gcc, to reduce code size. I learned this trick in AVR's application note AVR035 (page 14).
In the application note, they use the IAR compiler and bind the variable to an I/O register like this:
__no_init volatile uint8_t counter@0x35;

With avr-gcc, I can bind a variable to a standard register (r3 in this case) using this line:
register uint8_t counter asm("r3");

This does not work for I/O registers though. Is there a way to do this for I/O registers?

A: Since this works for global variables only, what about just using something like this to use, for example the Uart Baud Rate Register:
#define myGlobalVariable UBRR

Also note that this optimization is only worth it if you're doing a lot of bit testing, because there are direct bit testing instructions for most of the IO registers. Oh, I forgot that not all AVRs have the LDS and STS instructions and some access SRAM only through the Z register, which makes a big difference in both code size and speed compared to a simple IN and OUT...


text:
Q: How Facebook and other notifications work without gmail account in sync As per my knowledge as of now the only way of push notification in android is GCM, and to register a device on GCM we need a Gmail account to be synced on device so if I am developing an app using GCM for push notifications service I need to put a check of whether the Gmail account is configured and synced on device or not.
But the application like facebook, Twitter and many more never ask to add and sync a Gmail account then how they are able to use push notifications ?

A: if you have facebook fo you once logged in yhen its send push notification,
if you wants facebook for android go to http://goo.gl/CPLFl
there were also other paid applications for android in free.


text:
Q: Singleton class with Java enum for holding global states in a Multi-threaded application I need to share some global states (button status) between EDT and a bunch of worker threads. When the EDT changes the value, it needs to appear immediately in all other worker threads. I have designed a singleton class with Java enum as follows:
public enum ButtonState {
     INSTANCE;

     private volatile boolean showPhase = false;

     public boolean showPhase() {
          return showPhase;
     }

     public void setShowPhase(boolean showPhase) {
          this.showPhase = showPhase;
     }
}

//Client Code:
if (ButtonState.INSTANCE.showPhase()) {
      // show phase
      // do stuff
      ButtonState.INSTANCE.setShowPhase(false);
}

*

*Is this the correct way for achieving my goal or is there any other better approach?

*Do I really need to make the showPhase volatile?

A: It depends upon your use case if only requirement is to shared flag among the multiple thread your approach looks correct and thread safe as you are using volatile.So the change value will be visible to all thread.This is a pull model all worker thread needs to be access the flag by there own.
Or you can use push based model as suggested above to use Observer patter to push to all worker thread any changes in the flag.I think 2nd approach is good as it will notify the worker immediately and all thread will get the notification same time.In your approach may be there will be a delay .


text:
Q: Angularjs : make input = null when ng-hide = true Hello  i want to make the input text empty
when its become hidden (ng-hide="true")
i need dynamic solution work for multiple hidden inputs
so if some one checked Yes then entered child count
then if checked No  i need child count to become empty

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app>
<select ng-model="has_child">
<option value="1">Yes</option>
<option value="2">No</option>
</select>

<input type="text" ng-model="childcount" ng-hide="has_child == 2"/>
<input type="text" ng-model="mailcount" ng-hide="has_child == 2"/>
<input type="text" ng-model="femailcount" ng-hide="has_child == 2"/>
</form>

A:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app>
<select ng-model="has_child" ng-change='has_child == 2 ? childcount=null: ""'>
<option value="1">Yes</option>
<option value="2">No</option>
</select>

<input type="text" ng-model="childcount" ng-hide="has_child == 2"/>
</form>

A: use ng-change in your select
<select ng-model="has_child" ng-change="option()">

and add this function in your controller
$scope.option=function(){
    if($scope.has_child==2){
    $scope.childcount='';
    }
    console.log($scope.childcount);
}

Thanks


text:
Q: TClientDataSet - how to 'cancel' loadfromfile? I have a TClientDataSet that stores data in .cds format.
Let's say i did this :
clientDataSet1.loadFromFile('myclient.cds');

After i did this, is there a way to revert the loading and put the component in the state it was BEFORE i called this method, so i can add / delete fields that are not related to the .cds file ?
I suppose i need to use 'clearData' option , but i only can do this at design time, i did not found a way to call it in run time.

A: As you may know, SaveToFile and LoadFromFile exist mainly to support the CDS's
"Briefcase" mode of operation whereby you can work on a local copy of database records
while disconnected from the records' source database, save the changes locally
and then apply them once you reconnect to it. The saved file includes the change cache
of the CDS, so that you can do something like this:
 clientDataSet1.LoadFromFile('myclient.cds');
 clientDataSet1.UndoLastChange;

and that will revert the CDS's records to the state they were in prior to the
last change saved to the CDS before SaveToFile was called.
However, that is not quite what you asked, which seemed to me to be how to revert
the CDS to whatever state it was in prior to LoadFromFile being called, and at that
point it may have contained entirely different data.
If you want to be able to restore this prior state, you can do, provided
you take steps to save it before calling LoadFromFile.
Simplest would be
clientDataSet1.SaveToFile('myclient.prv');
clientDataSet1.loadFromFile('myclient.cds');

if ReloadPreviousVersion then
  clientDataSet1.loadFromFile('myclient.prv');

or, if you want to avoid saving to disk
var
  PrvData : OleVariant;
[...]
  PrvData := clientDataSet1.Data;
  clientDataSet1.loadFromFile('myclient.cds');

  if ReloadPreviousVersion then
    clientDataSet1.Data := PrvData;

(or you could save to/load from an in-memory stream).
Btw, I don't know whether you are familar with it, but CDSs have a SavePoint property which is very handy for backtracking and undoing changes; unfortunately SavePoints do not allow backtracking past operations like LoadFromFile and ApplyUpdates because these clear out the CDS's change cache.
Regarding your 'clearData' query, if you just want to clear out the CDS's data, just do
clientDataSet1.EmptyDataSet;


text:
Q: Use cauchy convergence theorem to prove that following sequences are convergent
I dont understand how xn - xm = highlighted part.
isnt it should be
$$ a_{n}q^{n} -  a_{m}q^{m} $$ ?
I understnad other steps. but I dont understnad how solution got highlited part.

A: Does this help?
$$\begin{align*}
x_n&=a_0+a_1q+\ldots+a_mq^m+a_{m+1}q^{m+1}+\ldots+a_nq^n\\
x_m&=a_0+a_1q+\ldots+a_mq^m\\ \hline
x_n-x_m&=\phantom{a_0+a_1q+\ldots+a_mq^m+}\;\,a_{m+1}q^{m+1}+\ldots+a_nq^n
\end{align*}$$


text:
Q: Skier, выводиться ошибка типа TypeError И снова здравствуйте!
Нашёл другой код, но опять ошибка:
File "C:\Users\user\Desktop\Python\Skier.py", line 23, in turn
    self.image = pygame.image.load(skier_images(list('D:\My Games\skier_images\self.angle')))
TypeError: 'list' object is not callable

Ошибка в данном коде:
#Поворачиваем лыжника
    def turn(self, direction):
        self.angle = self.angle + direction
        if self.angle < -2: self.angle = -2
        if self.angle > 2: self.angle = 2
        center = self.rect.center
        self.image = pygame.image.load(skier_images(list('D:\My Games\skier_images\self.angle')))
        self.rect = self.image.get_rect()
        self.rect.center = center
        speed = [self.angle, 6 - abs(self.angle) * 2]
        return speed

Знатоки! Обращаюсь к вам! Не будьте равнодушными! Заранее спасибо!


text:
Q: Предотвращение засыпания во время выполнения Как можно запретить отключение дисплея/засыпание/переход в ждущий режим или гибернацию ПК во время выполнения программы?
На ПК установлены следующие настройки схемы электропитания:
Отключение дисплея: 5 мин
Сон: 10 мин
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);

почему то все равно позволяет отключение дисплея.
Доп вопрос, не смог нагуглить, получает ли приложение какое-либо сообщение от системы (типа WM_***) перед тем, как система собирается заснуть?


text:
Q: Unique constraint violation when switching two unique fields in the same transaction in H2 I have a Spring Boot application using Spring Data repositories with entities mapped with JPA. The database is H2. The table is auto-generated. I'm doing two updates in the same transaction. Each of them would on its own would violate a unique constraint, but when both are applied together, the result should be fine. However, I'm still getting an exception.
I tried to do the same update with a DB tool (Database view in IntelliJ IDEA) to try to see if that would work, getting this error:
Unexpected update count received (Actual: 0, Expected: 1). All changes will be rolled back.

This is my entity in question:
@Entity
@Table(
        name = "DATA_SET_COLUMN",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = {"DATA_SET_ID", "ORDER_INDEX"})
        }
)
@Data
@EqualsAndHashCode(callSuper=true)
@NoArgsConstructor
@ToString(exclude = {"dataSet", "elements"})
public class DataSetColumn extends UniteFlowEntity {
    @Column(name = "ORDER_INDEX", nullable = false)
    private int order;

    @Column(name = "DATA_SET_ID", nullable = false)
    private String dataSetId;

    @ManyToOne(fetch= FetchType.LAZY)
    @JoinColumn(name="DATA_SET_ID", nullable = false, insertable = false, updatable = false)
    @JsonIgnore
    private DataSet dataSet;

    @OneToMany(mappedBy = "column", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JsonIgnore
    List<DataSetElement> elements;
}

Note the unique constraint on DATA_SET_ID and ORDER_INDEX.
I'm using a Spring Data repository for access:
@Repository
public interface DataSetColumnRepository extends JpaRepository<DataSetColumn, String> {}

Saving the entities looks something like this:
        repository.save(entity1);
        repository.save(entity2);

I have two DataSetColumns stored with the same DATA_SET_ID and want to switch the ORDER_INDEX (the one which has 0 gets 1 and vice versa). This happens in the same transaction (managed by Spring, as set up by Spring Boot).
My expectation was that the unique constraint would not be violated since after both updates the table should be valid. However, I'm getting this:
update unitelabs.data_set_column set creation_date=?, modification_date=?, data_set_id=?, order_index=? where id=? [23505-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.index.BaseIndex.getDuplicateKeyException(BaseIndex.java:101)
    at org.h2.mvstore.db.MVSecondaryIndex.requireUnique(MVSecondaryIndex.java:236)
    at org.h2.mvstore.db.MVSecondaryIndex.add(MVSecondaryIndex.java:202)
    at org.h2.mvstore.db.MVTable.addRow(MVTable.java:732)
    at org.h2.table.Table.updateRows(Table.java:509)
    at org.h2.command.dml.Update.update(Update.java:177)
    at org.h2.command.CommandContainer.update(CommandContainer.java:102)
    at org.h2.command.Command.executeUpdate(Command.java:261)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:199)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:153)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3356)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3229)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3630)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:146)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3283)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2479)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:98)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:532)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:533)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:304)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at uniteflow.dataset.api.rest.DataSetApi$$EnhancerBySpringCGLIB$$839b47f6.saveColumns(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)

Is my expectation wrong and this doesn't work in principle? Or could there be something wrong in my code?

A: Your expectation is wrong, to allow such modification the unique constraint should be explicitly defined as deferred (in databases that support optional feature F721) and H2 currently (as of 1.4.199) does not support this feature, there is a feature request for it:
https://github.com/h2database/h2database/issues/223
The typical workaround is to assign a some fake value to the first row, then change the second row to its new value and finally change the first row to its new value.


text:
Q: How can I hyperlink from PowerPoint to Excel, linking to a specific tab and named range or cell? How can I hyperlink from PowerPoint to Excel, linking to a specific tab and named range or cell and make it stick?
I am successful in creating the Hyperlinking and obtaining the desired results, however after I save the PowerPoint file, it deletes the tab and named range that were included in the Hyperlink.
As an example:

C:\<file name.xlsx>#<tab name>!<named range or cell>

.  This works great as entered and links properly until I save the PowerPoint file.
After a save, it truncates the hyperlink after file name.  It opens the Excel file to the last saved location.

A: Here is how i did it:

*

*Copy your cell/range in excel

*Go to powerpoint and click on Paste > Paste special

*Select paste link on the left

*Select attach hyperlink

Save the file and you are good to go.


text:
Q: MSVC contidion_variable clarification Could somebody clarify the meaning of the bold part on this remark? If possible with a code snippet.
I can't identify what's referred as calling thread and functions in this context.
Is there any difference with the behaviour of condition_variable on linux (gcc + pthreads) ?

Remarks
Code that waits for a condition variable must also use a mutex. A calling thread must lock the mutex before it calls the functions that wait for the condition variable. The mutex is then locked when the called function returns. The mutex is not locked while the thread waits for the condition to become true. So that there are no unpredictable results, each thread that waits for a condition variable must use the same mutex object.1

I've a bug that shows up only on Windows. notify_one() seems to be ignored but the code works OK if using wait_for() instead of wait() (still trying to produce an MCVE for that).

A: calling thread is the thread that makes the call to one of std::condition_variable::wait overloaded functions.


text:
Q: In Final Fantasy VII, does it matter where you equip your materia? I like to think of myself as an expert in the area of Final Fantasy VII.  As it was on steam for $8.00 recently, I bought a copy for my girlfriend.
I've been answering her questions with relative ease, but she asked me something that took me completely by surprise.
Does it matter which equipment slot you place your materia in?  It's something that I guess I never really gave thought to, and there isn't any information I can find online.

A: Regular materia does not matter in which slot you put it, you can put long range in your armor and still benefit from the long range materia in the same manner as if you had put it in your weapon. However, and i'm sure you know since you think of yourself as a expert, you have combine or support materia where you need to put it in a linked slot with a combination that works. Like "All&ICE" that let's you cast ice on all monsters on the field. Elemental materia does matter if you put it on armor or weapon, it can add elemental damage to your attacks or extra resistance to it when you put it in an armor.
Then you also have equipment that has an effect on the materia it holds, like double XP or none. So if you want to level your materia faster you should wear one of the double XP equipment.
The following is a list of some good combinations i fetched from www.uffsite.net
Added Effect + Contain
Weapon: Attacks can cause a number of status effects such as Petrify, Confuse, Berserk or sometimes Paralyze to one or more enemies.
Armor: User becomes immune to Petrify, Confuse, Berserk and Paralysis.
Added Effect + Destruct
Weapon: If you're lucky, the weapon will deal a death-strike.
Armor: User becomes immune to instant death attacks like cross-scissor.
Added Effect + Mystify
Weapon: Some attacks can cause Berserk or Confuse to an opponent. If it's the former, then that's not too good. However, the power of confusion is very handy to have.
Armor: Gives the user immunity to berserk and confused statuses.
Added Effect + Poison
Weapon: Some attacks can poison an enemy.
Armor: User becomes immune to poinson attacks.
Added Effect + Seal
Weapon: Gives a very good chance of silencing or putting an enemy to sleep.
Armor: Grants the user immunity to Silence and Sleep.
Added Effect + Time
Weapon: Some attacks slow or even paralyze the enemy.
Armor: Gives the user immunity to Slow and Paralysis.
Added Effect + Transform
Weapon: Some attacks inflict Mini or Frog on the enemy.
Armor: Gives user immunity to Mini and Frog status.
Elemental + Elemental Summon (Ifrit, Shiva, Titan...)
Weapon: Adds element of summon (Fire for Ifrit, etc.) to weapon.
Armor: Grants user 50% resistance to summon element (resistance to Ice with Shiva, etc.).
Pre-Emptive + Materia
Anywhere: Depending on how lucky you are and how levelled your pre-emptive materia is, you'll sneak on the enemy(ies) and use the action associated with the linked materia.
Final Attack + Anything
Before your character dies, he / she / it will perform the action associated with the linked materia. For example:
Final Attack + Revive
Anywhere: The most basic combo for your character's dying act - He / she / it will cast the Revive spell on themselves right before dying.
HP Absorb + Damage Dealing Materia
Anywhere: The linked materia attack will restore some of your HP. For example:
HP Absorb + Knights of the Round
Anywhere: When KoTR attacks the enemy and they die (because they will), you will gain a lot of HP from it.
MP Absorb + Damage Dealing Materia
Anywhere: Same as HP Absorb + Anything, except it restores MP and not HP.
MP Turbo + Materia
Anywhere: This will use more MP to make the attached materia more powerful. For example:
MP Turbo + Knights of the Round
Anywhere: If your Magic stats is pretty high, this will cause each knight to deal up to 9999 damage. This means 130,000+ damage altogether.
Quadra Magic + Materia
Anywhere: The attached magic or summon materia is performed four times for the cost of one, but does half damage with each casting.
Counter + Deathblow
Anywhere: Counter attacks with a deathblow to that enemy.
Counter + Manipulate
Anywhere: Counter attacks by manipulating the attacking enemy.
Counter + Steal
Anywhere: Counter attacks by stealing from the enemy.
Counter + Morph
Anywhere: Counter attacks by trying to morph the enemy into an item.


text:
Q: Calculate distinct of a table column plus two static values using DAX I have a tabular cube that I working on. I would like to get distinct values from "Column1" and then get two additional columns(to be created afresh) as static text one as "All" and other as "2020Q4".
Output would look like:

Column1
Column2
Column3

AA
All
2020Q4

BB
All
2020Q4

CC
All
2020Q4

DD
All
2020Q4

EE
All
2020Q4

Any help is appreciated. So far I am able to get distinct but unable to get associated static values.

A: Your can simplify the code:
EVALUATE
ADDCOLUMNS (
    DISTINCT ( TableName[Column1] ),
    "Column2", "All",
    "Column3", "2020Q4"
)

A: Finally able to do it as below:
 EVALUATE
       Addcolumns( DISTINCT(Tblname[Column1]), "Column2",
 SELECTCOLUMNS(Tblname, "Column2", SUBSTITUTE(Tblname[Column1],
 Tblname[Column1], "All")),
 "Column3", SELECTCOLUMNS(Tblname, "Column3", SUBSTITUTE(Tblname[Column1],
 Tblname[Column1], "2020Q4"))
 )


text:
Q: Why does systemd display certain service units that do not have an associated unit-file? I have been reading up and investigating systemd and systemctl on Debian 8 Jessie.
When running
$ sudo systemctl list-units --all --type=service

a few services appear in the list that have no unit-file associated to them such as:

● clamav-daemon.service | not-found | inactive | dead | clamav-daemon.service

● console-screen.service | not-found | inactive | dead | console-screen.service

● festival.service | not-found | inactive | dead | festival.service

● greylist.service | not-found | inactive | dead | greylist.service

● keymap.service | not-found | inactive | dead | keymap.service

● krb5-kdc.service | not-found | inactive | dead | krb5-kdc.service

Yet at the same time, when running
$ sudo systemctl list-unit-files --all --type=service

there are no unit-files associated to the above units.
My question is:
How can systemctl list these services as units (or even know that these units exist), if there are no unit-files that exist for these units?

A: Some unit "files" are created on the fly (for example for devices, their entries are also created by the kernel as the devices get initialized), and only ever exist in memory.


text:
Q: Initializing Chart Js Multiple times for and Array of Objects As the title suggests  here is a snippet of my code
angular.forEach($scope.students,function(){

  var ctx = document.getElementById("myChart").getContext("2d");
  var myRadarChart = new Chart(ctx).Radar(chartData);
  //Data//
  var subjects = [];
  var scores = [];

  angular.forEach(myData.subjects, function(subject){
    subjects.push(myData.subject.name);
  });

  angular.forEach($scope.data.subjects, function(score){
    scores.push(score.grades.assignments+score.grades.tests+score.grades.final);
  });

  var chartData = {
    labels : subjects,
    datasets : [
        {
        data: scores,
        fillColor: color2,
        strokeColor: color1,
        pointColor: color1,
        pointStrokeColor: color1,
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)"
      }
    ]
  };

  });

}]);

I have everything else working but Im not sure how to properly initialize each chart uniquely for each object in data.json , have a look

A: I would use a directive and it looks like there's already one out there for chart.js and AngularJS.  This way you can easily set up the data for each chart.


text:
Q: What is the exact difference between "called" and "so-called"? Actually, in English to Korean dictionary, both of "called" and "so-called" have the same meaning.
In many examples of the dictionary, "so-called" is used as adjective rather than past-particle, i.e., it is placed before the noun.
On the other hand, "called" is used as past particle many times.

However, recently I've frequently observed that the word "so-called" is used as past-particle like "called".

What is exact difference between called and so-called? (Not only meaning but also usage)
The following two sentences are the example I made:

Networks that consist of multiple mobile nodes are promising technology, so-called mobile ad hoc networks (MANETs).
Networks that consist of multiple mobile nodes are promising technology, called mobile ad hoc networks (MANETs).

A: The difference is slight.  Often, but not always, so-called is carries an air of disapproval, suggesting the name is in some way clumsy, inept or inappropriate.
Personally, I don't detect such a tone in your example.  Another way of signalling disapproval is the use of single inverted commas, sometimes called 'scare' quotes, because they say to the reader, "be careful, I am not committed to the bit between single quotes in any literal way".  This use of single quotes has also been called sneer quotes, for obvious reasons.  But in my experience, there are no hard and fast rules about this.
I myself should prefer called to so-called in the context you have given.  I doubt if the author meant to hint at disapproval of the acronym for a programming feature.

A: "Called" is a definition. Think of it like an equals sign.
"So-called" generally implies there's something not quite equal (e.g., "so-called leader" for someone in charge but doesn't actually lead). It can also be a common name that isn't its official name.


text:
Q: jquery ui greedy not working as it should So what i'm trying to do is to place an item( the diamond shaped item ) in the droppable and that item creates 2 sub-droppables in wich you place items, but the thing is i can't seem to get the "greedy" function to work with the generated droppables. Currently i'm only testing it on the second item - left side when generated.
my My jsFiddle .

This is the main dropzone.
            $(".objects").droppable({
            accept: "#block",
            drop: function (ev, ui) {
                $(".test").append('Dropped!');
            }});

This is the sub-dropzone. On drop there should appear Dropped123! in the bottom code paragraph.
          $(".true").droppable({
                greedy:true,
                accept: "#block",
                drop : function (ev, ui) {
                    $(".test").append('Dropped123!');

                }
            });

A: Your problem is that you are trying to bind droppable before you actually have the elements, I have changed your fiddle so now you bind the event to the actual element:
http://jsfiddle.net/L22d4x2x/7/
                var divTrue = $('

');
                $(".n_block"+ cloneCount1 ).append(divTrue);
                divTrue.droppable({
                    greedy:true,
                    accept: "#block",
                    drop : function (ev, ui) {debugger;
                        $(".test").append('Dropped123!');

                    }
                });


text:
Q: Java -- Runtime typing differences I have two situations drawn up, and the strange differences between them are causing me a bit of grief.  I will attempt to detail them below in code.
Situation 1:
public void doSomething(Object obj) {
  //do something with obj
}

public void doSomething(String str) {
  //do something similar to str, but apply some custom
  //processing for String's
}

Object o = new String("s");
doSomething(o); // this will use the Object version...

Situation 2:
class Dog {
  void makeSound() {
    System.out.println("woof");
  }
}

class Chihuahua extends Dog {
  void makeSound() {
    System.out.println("yip");
  }
}

Dog dog = new Chihuahua();
dog.makeSound(); //will print 'yip', the Chihuahua version...

Why, in situation one, is the runtime type of the parameter not used, but in situation two it is?  I understand that the examples are actually different things, but I am more curious about what is going on 'under the covers' here.

A: In the first example, a method signature is chosen at compile-time from among a number of overloaded signatures.  The Java language specification says that this is done based on the static type of the variables.
In the second example, an implementation of a given method signature is chosen at runtime based on virtual method dispatch.  This is done based on the runtime type of the class containing the method definition.

A: Situation #1 is method overloading, which is static at compile time.  Situation #2 is polymorphism, which is dynamic at runtime.


text:
Q: Unable to call controller action from a partial view rendered via ajax i have the following set up :
A) HTML div container in Parent View to hold partial view returned:

B) Controller method that returns the view model -
    [HttpGet]
    public PartialViewResult GetProjectCostsById(int viewProjectId)
    {
        return PartialView("ProjectCost", GetProjectCostsViewModel(viewProjectId));
    }

C) AJAX to render the partial view HTML into the div above -
$(document).ready(function () {

    $(".retProjTran").click(function () {

        var projectid = $(this).data("projectid");

        $.ajax({
            cache: false,
            asynch: true,
            type: "GET",
            url: "@(Url.Action("GetProjectCostsById", "Project"))",
            data: { "viewProjectId": projectid },
            success: function (retData) {
                $('#divProjectCostList').html(retData);
            }
        })
    });
})

The above works just fine.
the Partial view set up in order to get elements from the returned model and render these in a table
@using (Html.BeginForm("ProjectCostList", "Project", FormMethod.Get))
{

        @foreach (var item in Model)
        {

                @Html.HiddenFor(modelItem => item.ProjectCostType)

                    @Html.ActionLink(item.ProjectCostType.ToString(), "", null,
                     new { @class = "retProjDetails", data_details = item.ProjectCostId })

        }

}

This Partial view also needs to access a JS method  -
$(".retProjDetails").click(function () {

        $.ajax({
            cache: false,
            asynch: true,
            type: "GET",
            url: "@(Url.Action("GetProjectCostDetails", "Project"))",
            data: { "viewProjectCostId": projectCostId },
            success: function (retData) {
            $('#divProjectCostList').html(retData);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(thrownError);
            }
        })
    });

I can see the JS function being called from the rendered Actionlink, however the relevant Controller action is simply not hit..
I'd imagine this is some sort of issue with how I am rendering the Partial, but cannot figure out what. Hope someone can provide a clue. Happy for any suggestions on whether this set up is optimal or I need to change..

A: You simply change your
@using (Html.BeginForm("ProjectCostList", "Project", FormMethod.Get))

to
@using (Html.BeginForm("ProjectCostList", "Project", FormMethod.Post))

in the Partial View and things will be fine.


text:
Q: non-webkit browsers ignore @media queries with webkit-specific features I'm trying to pass the following @media query, but it's ignored in all non-webkit browsers:
@media not all and (-webkit-transform-2d) and (-webkit-transform-3d) and (-webkit-transform) {[...]}

What I expect to happen is that all webkit browsers that do not return true to all three features are passed, which is also what happens.
Likewise, based on Safari documentation on @media queries, I expect all non-webkit browsers to return false on all three features since they don't support them, but the @media query is ignored instead.
I had a look at the W3C documentation, but I'm not sure how to interpret it correctly.
Can someone help me find the error or another way to style elements in browsers that do not return true in the query?
I'm not interested in JavaScript solutions.
Thank you.
Incidentally, vendor-specific @viewport queries were also ignored for some reason.

A: You could, instead use the conditionnal rules  @support:
http://www.w3.org/TR/css3-conditional/#at-supports


text:
Q: Отличие try...catch от throws В чем принципиальное отличие
try {

}catch(Exception e){

}

от throws

A: При обработке исключений всегда есть 2 варианта : либо пробрасываем выше (т.е. добавляем throws к сигнатуре метода), либо обрабатываем "на месте", используя try-catch

A: Вопрос в том где вам удобнее произвести эту обработку. try-catch как раз для этой обработки и служит, но не всегда удобно обрабатывать исключение в том месте где оно бросается.
throws позволяет не обрабатывать исключение в том месте которое его вызывает, а переложить эту работу на то место в коде где вы будете  вызывать метод через сигнатуру которого вы это исключение пробросили.
На пример:
a() {
    try {
    // какой-то код который может выбросить исключение
    } catch (Exception e) { ... }
}

b() {
    a(); // и тут не каких исключений не надо ловить вы его уже поймали
}

Или если вы не хотите ловить в методе a() то вы можете сделать так:
a() throws Exception {
    // какой-то код который может выбросить исключение но мы его пробрасываем

}

b() {
    try {
        a();// и ловим тут потому что в методе a() мы это делать не стали
    } catch (Exception e) { ... }
}

Во втором примере мы могли бы еще дальше его пробрасывать написав b() throws Exception вплоть до метода main и вообще его не ловить, но так лучше не делать.
То есть исключение это места где java говорит: тут может быть проблема, а вы должны что-то ответить, на пример: да здесь и обработаем и пишите try-catch или нет здесь не хочу давай потом и с помощью throws откладываете решение.

A: Тоже возник подобный вопрос, решил потестить. Вот пример кода:
    public class Exeptions {

    static void throwOne() {   // не указан throws
        System.out.println("В теле метода throwOne()");
        throw new NullPointerException("нулпоинтер");
    }

    public static void main(String[] args) {
        try {
            throwOne();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        System.out.println("Возвращение в main");
    }
}

Результат:
    В теле метода throwOne()
java.lang.NullPointerException: нулпоинтер
    at Exeptions.throwOne(Exeptions.java:6)
    at Exeptions.main(Exeptions.java:16)
Возвращение в main

Как видно все прекрасно скомпилировалось, но если выкинуть любое проверяемое исключение и не прописать throws - компилятор выдаст ошибку.
Итог: "обязательно указывать throws для всех исключений, кроме тех, которые относятся к классам Error и RuntimeException или любым их подклассам.
Все остальные исключения, которые может сгенерировать метод, должны быть
объявлены в операторе throws. Если этого не сделать, то во время компиляции
возникнет ошибка." - Шилдт.


text:
Q: Get last commit which leads to a merge I have two branches (development and main). From time to time the development branch gets merged into the main branch.
So there are merge commits like Merge branch 'development' into 'main'.
Now I do need the commit hash from the last development commit, which leads to the merge commit - not the merge commit itself, which is on the master branch. Is that possible?
Doing something like git log --merges origin/master --oneline --grep='^Merge branch development into main' -1 gives me the merge commit on the master branch, but I need the commit before this one (on the development branch).

A: Since you have the merge commit, you can do a:
git log <mergeCommit>^2 -1

That would give you the last development commit leading to that merge.
It uses the git rev-parse <rev>^[<n>] notation
In a bash session
git log -1 \
 $(git log --merges origin/master --format=format:%H --grep='^Merge branch development into main' -1)^2


text:
Q: bags of words object recognition for large datasets I'm implementing object recognition with bags of words histograms. The histograms are composed of 200 "words" per image, kmeans from the descriptors. The problem is that for a large dataset, say 5000 images, we suddenly have 200x5000=1,000,000 words in a histogram. This means that every object will be represented by a 1,000,000 length histogram.
This gets too big and cumbersome past some point. Is there someway around this?

A: Generally, you choose a codebook size that is independent of the number of training images. You would build the codebook by running k-means (or some other dictionary learning method) over a set of descriptors extracted from all the training data.
So, in your example, if you had 5000 training images, and approximately 1000 descriptors extracted from each image, that would give you 5,000,000 descriptors that you could cluster using k-means.
That could be very time-consuming, so you may choose to cluster using a random subset of the descriptors.