text:
Q: progress bar not progressing I have a program which is updating a table in sqlserver, I have a form which I want to show the progress of this, the progress bar is incrementing but this is not being displayed. do i need to use background worker for this? example of what im doing
public void updateTable(string tableName)
{
  // con is an instance of my form to access progressbar
  con.progressBar1.Minimum = 1;
  con.progressBar1.Step = 1;
  string dbQuery = "select summet from someting"

  con.progressBar1.Maximum = address.Tables[0].Rows.Count;
  MessageBox.Show("progress bar max " + con.progressBar1.Maximum);

   foreach (DataRow LonLat in address.Tables[0].Rows)
   {
       con.progressBar1.PerformStep();
       MessageBox.Show(con.progressBar1.Value.ToString()); // this is incrementing
       //plus updating table

   }

}

A: Short answer, yes. If you do it from the main thread you won't see the progress bar update.
Long answer:
Whenever you modify the user interface from a piece of your code that's translated into a "message" into the window message queue that will get that message and update the UI accordingly in the main thread.
However, since the main thread is busy handling your piece of code it doesn't have the "time" to actually update the user interface, and only when your process is done, it's free to update the user interface. That's why you see the progress bar going from 0% to 100% without any intermediate steps.
What you should do:
What you wanna do is put the work into a background worker, that way the main thread is free to attend UI update requests... that's, by the way, a standard practice if you wanna keep the UI responsive.

A: Yes you should use Background Worker, however it might not help, we would need to see bindings and everything else, to use background worker use something like this:
Window.Dispatcher.BeginInvoke((Action)(() =>
        {
            con.progressBar1.PerformStep();
        }

A: yes you have to use background worker
BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (o, ea) =>
    {
     // your code goes here
       }
 worker.RunWorkerCompleted += (q, ea) =>
    {
      }
 worker.RunWorkerAsync();

A: That happens if we cannot use a BackgroundWorker. I have a form with a progress bar whose only job is to accept a command to PerformStep, from some other form that opens it, and the form must simply do that. Both forms are in the GUI thread.
Nevertheless I don't get a consistent behavior from the progressbar. In the code below the progressbar is always one step behind than what its Value Property Signifies:
public partial class Form1 : Form
   {
      private readonly int m_numOfSteps;

      public Form1(int numOfSteps)
      {
         m_numOfSteps = numOfSteps;
         InitializeComponent();
      }

      private void Form1_Load( object sender, EventArgs e )
      {
         progressBar1.Step = (int)Math.Ceiling( 100.0 / m_numOfSteps );
      }

      public void DoStep(string msg)
      {
         progressBar1.PerformStep();
         label1.Text = msg;
         label2.Text = String.Format( "{0}%", progressBar1.Value  );
         label1.Refresh();
         label2.Refresh();
      }
   }

   public partial class Form2 : Form
   {
      public Form2()
      {
         InitializeComponent();
      }

      private void button1_Click( object sender, EventArgs e )
      {
         using( Form1 f = new Form1( 3 ) )
         {
            f.Show();
            f.Refresh();
            Thread.Sleep( 1000 );
            f.DoStep( "AAAA" );
            Thread.Sleep( 1000 );
            f.DoStep( "BBBB" );
            Thread.Sleep( 1000 );
            f.DoStep( "CCCC" );
            Thread.Sleep( 1000 );
         }
      }
   }


text:
Q: Change markup of content search webpart I've inserted an content search webpart but the items are being displayed very ugly:

I know there is a dropdown list where you can select the styling. But this just isn't working for me:

What I want is a clean simple list with only the item names. Like a normal list/document library.
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linear programming. How can I add a constraint that is not constant value ? (like the allocation for each ad <= budgets, both two sides can change) I am building an optimal model using linear programming like below:
m = gp.Model("allocation_budget")

#keywords are given tuple about keyword in ad.{UK retail, free shipping UK etc.}
allocation = m.addVars(keywords, lb = 0, name="allocation")
# budgets = np.arange(0,1100000,100000)
budget = m.addVars(budgets, lb = 0, name="budget")

#the right side of equation is wrong, it's where I am confused about
budget_constraint = m.addConstr(allocation.sum() <= budget,"budget_constraint")

#the objective is to maximize the net revenue which is equal to 4/CPC[k]*allocation[k] - budget, but I don't know to fit the variable "budget" into this equation
m.setObjective(quicksum(4/CPC[k]*allocation[k] - budget), GRB.MAXIMIZE)

#the following code contain error as well due to the previous problem
def printSolution():
    if m.status == GRB.OPTIMAL:
        print('\nClicks: %g' % m.objVal)
        print('\nAllocation:')
        allocationx = m.getAttr('x', allocation)
        for k in keywords:
                print('%s %g' % (k, allocationx[k]))
        print("\nBudget: ",budget.x)
    else:
        print('No solution:', m.status)
m.optimize()
printSolution()

The objective is to find the right budget values so that the net revenue can be maximized.
Any help will be great! Please help


text:
Q: PostgreSQL save database data im working in a netbeans project and i need to save the data from a postgreSQL every day, so i can send it to a secure folder in the network.
Is there anyway to do that, save the data or the entire database (Script + Data).
Software: Netbeans JDK 6 , postgreSQL 9.4

A: I'd look into a scheduled backup for your db, and version control for your code


text:
Q: Target-typed new expressions and implicit arrays I can write the following to initialize a List<KeyValuePair<string, string>> in a field initializer:
List<KeyValuePair<string, string>> lst = new() {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}

leveraging target-typed new expressions for both the containing List<> and the individual KeyValuePair<> structs.
Is it possible to similarly initialize an array? Target-typed new expressions can't be used for the array itself, because an array has to be initialized.
But the following -- using implictly-typed arrays -- doesn't compile:
KeyValuePair<string, string>[] arr = new [] {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}

with:

CS0826 No best type found for implicitly-typed array

A: You can remove the new[] part:
using System.Collections.Generic;

KeyValuePair<string, string>[] arr =
{
    new("Key1", "Value1"),
    new("Key2", "Value2")
};

That's only valid as part of a variable declaration though, which allow an array_initializer as the initial value, without the need for an array_creation_expression. Variable declarations include fields, of course:
public class Test
{
    private readonly KeyValuePair<string, string>[] arr =
    {
        new("Key1", "Value1"),
        new("Key2", "Value2")
    };
}


text:
Q: How do I extract part of a tuple that's duplicate as key to a dictionary, and have the second part of the tuple as value? I'm pretty new to Python and Qgis, right now I'm just running scripts but I my end-goal is to create a plugin.
Here's the part of the code I'm having problems with:
import math

layer = qgis.utils.iface.activeLayer()
iter = layer.getFeatures()
dict = {}

#iterate over features
for feature in iter:
    #print feature.id()
    geom = feature.geometry()
    coord = geom.asPolyline()
    points=geom.asPolyline()
#get Endpoints
    first = points[0]
    last = points[-1]

#Assemble Features
dict[feature.id() ]= [first, last]

print dict

This is my result :
    {0L: [(355277,6.68901e+06), (355385,6.68906e+06)], 1L: [(355238,6.68909e+06), (355340,6.68915e+06)], 2L: [(355340,6.68915e+06), (355452,6.68921e+06)], 3L: [(355340,6.68915e+06), (355364,6.6891e+06)], 4L: [(355364,6.6891e+06), (355385,6.68906e+06)], 5L: [(355261,6.68905e+06), (355364,6.6891e+06)], 6L: [(355364,6.6891e+06), (355481,6.68916e+06)], 7L: [(355385,6.68906e+06), (355501,6.68912e+06)]}
As you can see, many of the lines have a common endpoint:(355385,6.68906e+06) is shared by 7L, 4L and 0L for example.
I would like to create a new dictionary, fetching the shared points as a key, and having the second points as value.
eg : {(355385,6.68906e+06):[(355277,6.68901e+06), (355364,6.6891e+06), (355501,6.68912e+06)]}
I have been looking though list comprehension tutorials, but without much success: most people are looking to delete the duplicates, whereas I would like use them as keys (with unique IDs). Am I correct in thinking set() would still be useful?
I would be very grateful for any help, thanks in advance.

A: Maybe this is what you need?
dictionary = {}
for i in dict:
    for j in dict:
        c = set(dict[i]).intersection(set(dict[j]))
        if len(c) == 1:
            # ok, so now we know, that exactly one tuple exists in both
            # sets at the same time, but this one will be the key to new dictionary
            # we need the second tuple from the set to become value for this new key
            # so we can subtract the key-tuple from set to get the other tuple
            d = set(dict[i]).difference(c)
            # Now we need to get tuple back from the set
            # by doing list(c) we get list
            # and our tuple is the first element in the list, thus list(c)[0]
            c = list(c)[0]
            dictionary[c] = list(d)[0]
        else: pass

This code attaches only one tuple to the key in dictionary. If you want multiple values for each key, you can modify it so that each key would have a list of values, this can be done by simply modifying:
# some_value cannot be a set, it can be obtained with c = list(c)[0]
key = some_value
dictionary.setdefault(key, [])
dictionary[key].append(value)

So, the correct answer would be:
dictionary = {}
for i in a:
        for j in a:
            c = set(a[i]).intersection(set(a[j]))
            if len(c) == 1:
                d = set(a[i]).difference(c)
                c = list(c)[0]
                value = list(d)[0]
                if c in dictionary and value not in dictionary[c]:
                    dictionary[c].append(value)
                elif c not in dictionary:
                    dictionary.setdefault(c, [])
                    dictionary[c].append(value)

            else: pass

A: See this code :
dict={0L: [(355277,6.68901e+06), (355385,6.68906e+06)], 1L: [(355238,6.68909e+06), (355340,6.68915e+06)], 2L: [(355340,6.68915e+06), (355452,6.68921e+06)], 3L: [(355340,6.68915e+06), (355364,6.6891e+06)], 4L: [(355364,6.6891e+06), (355385,6.68906e+06)], 5L: [(355261,6.68905e+06), (355364,6.6891e+06)], 6L: [(355364,6.6891e+06), (355481,6.68916e+06)], 7L: [(355385,6.68906e+06), (355501,6.68912e+06)]}
dictionary = {}
list=[]
for item in dict :
   list.append(dict[0])
   list.append(dict[1])

b = []

[b.append(x) for c in list for x in c if x not in b]
print b # or set(b)
res={}

for elm in b :
   lst=[]
   for item in dict :
       if dict[item][0] == elm :
           lst.append(dict[item][1])
       elif dict[item][1] == elm :
           lst.append(dict[item][0])
   res[elm]=lst

print res


text:
Q: JavaFX null pointer exception at label.setText() sorry. I don't speak english well so please understand me
I'm making smartmirror for java but I have problem with setText() function.
after calling weather api and saving location name to variable, I start label.setText() but it has null pointer exception.
I heard about platform.run later() method and task , but they don't work.
please help me T.T
There are my source
package SmartMirror.main;

import java.io.IOException;
public class SpeechClass {
WeatherController weather = new WeatherController();

// Logger
private Logger logger = Logger.getLogger(getClass().getName());

// Variables
public String result;

// Threads
Thread  speechThread;
Thread  resourcesThread;
Thread  openThread;

// LiveRecognizer
private LiveSpeechRecognizer recognizer;

protected String location;

public void Speech(){
    // Loading Message
    logger.log(Level.INFO, "Loading..\n");

    // Configuration
    Configuration configuration = new Configuration();

    // Load model from the jar
    configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
    configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");

    // if you want to use LanguageModelPath disable the 3 lines after which
    // are setting a custom grammar->

    // configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin")

    // Grammar
    configuration.setGrammarPath("resource:/grammars");
    configuration.setGrammarName("grammar");
    configuration.setUseGrammar(true);

    try {
        recognizer = new LiveSpeechRecognizer(configuration);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    // Start recognition process pruning previously cached data.
    recognizer.startRecognition(true);

    // Start the Thread
    startSpeechThread();
    startResourcesThread();

}

/**
 * Starting the main Thread of speech recognition
 */
protected void startSpeechThread() {

    // alive?
    if (speechThread != null && speechThread.isAlive())
        return;

    // initialise
    speechThread = new Thread(() -> {
        logger.log(Level.INFO, "You can start to speak...\n");
        try {
            while (true) {
                /*
                 * This method will return when the end of speech is
                 * reached. Note that the end pointer will determine the end
                 * of speech.
                 */
                SpeechResult speechResult = recognizer.getResult();
                if (speechResult != null) {

                    result = speechResult.getHypothesis();

                    System.out.println("You said: [" + result + "]\n");

                    if(result.equals("one")){
                        System.out.println("startOpenThread");
                        startWeatherThread();
                        openThread.sleep(3000);

                        Platform.runLater(new Runnable(){
                            @Override
                            public void run(){
                                weather.setLabel();
                                openweather();
                            }
                        });

                    }
                    // logger.log(Level.INFO, "You said: " + result + "\n")

                } else
                    logger.log(Level.INFO, "I can't understand what you said.\n");

            }
        } catch (Exception ex) {
            logger.log(Level.WARNING, null, ex);
        }

        logger.log(Level.INFO, "SpeechThread has exited...");
    });

    // Start
    speechThread.start();

}

/**
 * Starting a Thread that checks if the resources needed to the
 * SpeechRecognition library are available
 */
protected void startResourcesThread() {

    // alive?
    if (resourcesThread != null && resourcesThread.isAlive())
        return;

    resourcesThread = new Thread(() -> {
        try {

            // Detect if the microphone is available
            while (true) {
                if (AudioSystem.isLineSupported(Port.Info.MICROPHONE)) {
                    // logger.log(Level.INFO, "Microphone is available.\n")
                } else {
                    // logger.log(Level.INFO, "Microphone is not
                    // available.\n")

                }

                // Sleep some period
                Thread.sleep(350);
            }

        } catch (InterruptedException ex) {
            logger.log(Level.WARNING, null, ex);
            resourcesThread.interrupt();
        }
    });

    // Start
    resourcesThread.start();
}

protected void startWeatherThread() {
    try{
        openThread = new Thread(() -> {
            weather.Weather(); // 날씨를 변수에 저장

        });

    } catch (Exception e){

    }
    // Start
    openThread.start();
}

public void openweather(){
    Stage dialog = new Stage(StageStyle.TRANSPARENT);
    dialog.initModality(Modality.WINDOW_MODAL);
    dialog.initOwner(null);

    Parent parent = null;
    try {
        parent = FXMLLoader.load(WeatherController.class.getResource("weather_scene.fxml"));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Scene scene = new Scene(parent);
    dialog.setScene(scene);
    dialog.setResizable(false);
    dialog.show();
}

}

package SmartMirror.Weather;

import java.io.BufferedReader;

public class WeatherController {

@FXML private Label labelLocation;

public String locationResult="", weatherResult="", tempResult="";

    //날씨 API
    public void Weather() {
         try{

            //OpenAPI call하는 URL
            String urlstr = "http://api.openweathermap.org/data/2.5/weather?"
                        +"q=Chuncheon"
                        +"&appid=f1bccf50c733316db790a00a2d5165c6&units=metric";
            URL url = new URL(urlstr);
            BufferedReader bf;
            String line;
            String result="";

            //날씨 정보를 받아온다.
            bf = new BufferedReader(new InputStreamReader(url.openStream()));

            //버퍼에 있는 정보를 문자열로 변환.
            while((line=bf.readLine())!=null){
                result=result.concat(line);
                //System.out.println(line);
            }

            //문자열을 JSON으로 파싱
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObj = (JSONObject) jsonParser.parse(result);

            //날씨 출력
            JSONArray weatherArray = (JSONArray) jsonObj.get("weather");
            JSONObject weather = (JSONObject) weatherArray.get(0);

            //온도출력
            JSONObject mainArray = (JSONObject) jsonObj.get("main");
            double ktemp = Double.parseDouble(mainArray.get("temp").toString());

            locationResult = (String) jsonObj.get("name");
            weatherResult = (String) weather.get("main");
            tempResult = Double.toString(ktemp) + "℃";

            System.out.println("startWeatherThread" + locationResult);

            bf.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }

    }

    public void setLabel(){
        Platform.runLater(new Runnable(){
            @Override
            public void run(){
                System.out.println(locationResult);
                labelLocation.setText(locationResult);
            }
        });

    }

}

A: First of all, I'm not recommending on using public attributes, I suggest you to check Why use getters and setters? so change your 3 public field to a private ones and then make getters and setters to them.
About your problem, I haven't seen your fxml code for it, but make sure you gave your label an identity also known as fx:id so it wouldn't cause it to be null.
Also make sure that you gave reference to your WeatherController in fx:controller


text:
Q: Java: Updating GUI element during timed loop At home, expanding on a class assignment from this winter, trying to get it to update a GUI element during run time in order to show progress thought he loop.
Intended functionality is that, as it goes through a string, processing each char, a JLable that's been passed in from the GUI class updates on each loop iteration to show progress through the String. However, what happens is it only changes what's displayed on the label after the loop, after the final Thread.sleep(1000) expires (I don't know if it's before or after the synthesizer closes, don't think it would be related :/ ).
At this point, I'd like advice on how to get the JLabel 'progress' to change to the "Should show" text before the loop expires - some code unrelated to my problem has been removed to protect the efficient.
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.MidiChannel;
import javax.swing.JLabel;

public class SoundPlayer {

 /*Deceleration of private variables for the class*/

/*Constructor that assighns variables and triggers doPlay()method.
There is a reference to the JLabel 'Progress' passed in and declared beforehand,
 so there is access.*/
}

public void doPlay() {
    int totalSound;
    playNumTimes = 1;
    defaultTime = true;
    sound = 0;
    extraSound = 0;

    try {   //Opens ability to play the music.
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open();       //Will likely play sound, so opens channel.
        MidiChannel[] channels = synth.getChannels();

        musicNotes += ".";  //illegal character will mark end of string to play.

        //Examines each char of the String and acts accordingly.
        for (count = 0; count < musicNotes.length(); count++) { //For each char in the input.

            if (processChar(musicNotes.charAt(count))) { //If processed char is illegal and triggers a sound, play it!
                totalSound = extraSound + sound;    //Combines from given note and the < and >s.

                progress.setText("Should show");

                //PLAYS SOUND HERE!
                channels[channel].noteOn(totalSound, volume);
                Thread.sleep(300 * playNumTimes);   //Plays sound a number times equal to times.
                channels[channel].noteOff(totalSound);

                //After plays, resets values.
                playNumTimes = 1;
                defaultTime = true;
                sound = 0;      //Sound of 0 used to indicate no char has been assigned to the sound.
            }
        }
        Thread.sleep(1000);     //Wards against synthesizer from being closed prematurely and cutting off sound.
        synth.close();  //Closes after loop is finished.
    }
    catch (Exception e){
        e.printStackTrace();
    }
}


text:
Q: Migrating old database to new database I am installing new bugzilla server and importing old database to new bugzilla server
old mysql Server version : mysql  Ver 14.12 Distrib 5.0.51a, for debian-linux-gnu (x86_64) using readline 5.2
old OS Version:  Debian GNU/Linux 5.0 \n \l
New Mysql Server Version : mysql  Ver 14.14 Distrib 5.5.49, for debian-linux-gnu (x86_64) using readline 6.3
New OS Version: Debian GNU/Linux 8 \n \l
I am importing database like below
mysql -u root -p bugs < /home/chelsio/backup-05-25-2016-19-00.sql
I am getting below error
ERROR 1005 (HY000) at line 6237: Can't create table 'bugs.bugs' (errno: 150).
SHOW ENGINE INNODB STATUS; output
LATEST FOREIGN KEY ERROR
160527 10:27:59 Error in foreign key constraint of table bugs/bugs:
 FOREIGN KEY (component_id) REFERENCES components (id) ON UPDATE CASCADE,
  CONSTRAINT fk_bugs_product_id_products_id FOREIGN KEY (product_id) REFERENCES products (id) ON UPDATE CASCADE,
  CONSTRAINT fk_bugs_reporter_profiles_userid FOREIGN KEY (reporter) REFERENCES profiles (userid) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=30401 DEFAULT CHARSET=utf8:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
I dont have any knowledge on mysql I am new mysql world. Please help.


text:
Q: Redux saga - can't dispatch action: __webpack_require__.i(...) is not a function I am trying to dispatch an action in a saga function in this way:
yield put(addToCart(item));

When trying to execute it, it gives the error __webpack_require__.i(...) is not a function.
"addToCart" is an action creator which I imported:
  export const addToCart = product => ({
        type: types.ADD_TO_CART,
        payload: { product },
    });

This action never fires.
The item (or product) is an object, like :
{
    'id' : 5,
     'thing' : 'stuff'
}

(+ other properties).
I can dispatch other actions, but this one doesn't work for some reason.

A: I had imported the action creator wrongly:
import addToCart  from './actionCreators'

It should be:
import { addToCart } from './actionCreators'

But what kind of error is "__webpack_require__.i(...) is not a function" ? The error messages are worthless, they give you no clue at what the error is about.


text:
Q: how to delegate on ready function I know jquery support delegate function for add and remove a function custom follow event. EX
$("body").delegate("#p", "click", cfunc);

but how to delegate function when page loaded ?
edited------
I show more ex code for more detail in my question: :)
i have a function custom name = cfunc()
now i need call it when page load for run many many event inside it.
on the time page loaded, viewer make some event (ex: resize, scroll ...) i need undelegate cfunc() and call again with some new var.
--- edit 2 -----
sorry everyone, i will write done more code :
this is function i want to delegate
function bbbb_scroll(pos)
    {
        $(document).scroll(function() {
            var _currentpos = $(window).scrollTop();

            if (_currentpos > pos) {
                console.log('match');
            }
        });
    }

now i want add it on to page when stage READY
$(document).ready(function() {
        $(window).delegate("body", "resize", bbbb_scroll);
    });

after all, when user resize the window of browser, i need undelegate bbbb_scroll function and call again with new var ( on pos variable  )

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

    var position = 100;

    var scrollCallback = function(pos){

        var _currentpos = $(window).scrollTop();

        if (_currentpos > pos) {
            console.log('match');
        }
    };

    var resizeCallback = function(){

        $(document).unbind('scroll');

        $(document).on('scroll', function(){

            scrollCallback(position);

        });
    };

    $(window).on('resize', resizeCallback);

});

http://api.jquery.com/on/
http://api.jquery.com/ready/

A: Pretty obvious this one
Have a look at jQuery documentation
$(document).ready(function(){
    //- do your stuff
});

A: You delegate a function to run when the document loads by passing a function (either anonymously or by name) to the ready method
Anonymous method:
$(document).ready(function(){
   ...
});

named function
function myReadyHandler(){..}

$(document).ready(myReadyHandler);


text:
Q: Add Objects to NSMutableArray in a Loop I have problems getting NSMutableArray to work. I simplified the code for illustrating my problem. I have a class, which I use as a Data container.
@interface Question : NSObject {
int questionID;
NSString* text;
}

@property int questionID;

@property(nonatomic,retain)NSString* text;

@end

I am creating different instances of this container as follows:
.h
#import "Question.h"

@interface testViewController : UIViewController {
NSMutableArray* questions;
}

-(IBAction) start;

.m
....
- (void)viewDidLoad {
    [super viewDidLoad];
    questions=[[NSMutableArray alloc]init];
    for (int i=0; i<5; i++) {
      int questionID=i;
      Question* question=[[Question alloc]init];
      question.questionID=questionID;
      question.text=[NSString stringWithFormat:@"text %d",i];
      [questions addObject:question];
      [question release];
    }
}

..........
-(IBAction) start{
   for (int i=0; i<[questions count]; i++) {
       Question *theQuestion;
       theQuestion=(Question*)[questions objectAtIndex:i];
       NSLog(@"%d",theQuestion.questionID);
       NSLog(@"%@",theQuestion.text);
       NSLog(@"----------------------");
   }
}

In ViewDidLoad instances of question are created in a loop and they are added to the NSMutableArray questions. After question has been added it is released. After populating the NSMutableArray a function start is executed by pressing a button on the UI. This function should print out the contents of the different questions.
The  problem is when the function start is executed the NSMutableArray questions does not have the contents stored before and the program crashes on
NSLog(@"%d",theQuestion.questionID);

The interesting thing is that if I do not release the question on the function viewDidLoad, then everything works fine. However, I would miss releasing a variable I previously allocated and this should lead to a leak.
Does anybody has an idea how to do this properly?

A: It's quite possible that your issue lies elsewhere in your code, memory issues expose themselves in strange ways. Are you sure nothing else interacts with questions and its contents? I suggest you add a breakpoint to the code and explore its contents at the point of the crash.

A: When creating Question delete release and use this instead:
Question* question=[[[Question alloc]init] autorelease];

Also it might be a good idea to use autorelease pool here.


text:
Q: C: pop function in double linked list I am working with a double linked list and I have run into a problem with my pop() function.
//QueueElement describe the block in the cache
typedef struct _queue_ele_
{
    char *content;   //the data of the block
    struct _queue_ele_ *prev;
    struct _queue_ele_ *next;
}QueueElement;

typedef struct _queue_
{
    int queue_len;
    int max_queue_size;
    QueueElement *head;
    QueueElement *tail;
}MyQueue;

The pop function works until there is an input of 2 elements ( I clear the queue by poping one by one and freeing the memory)
pop:
// head is removed and returned
QueueElement* pop(MyQueue* myqueue)
{
    // if empty
    if(myqueue->queue_len == 0) return NULL;

    QueueElement *p = myqueue->head;

    // if one element
    if(myqueue->queue_len == 1)
    {
        myqueue->queue_len--;
        myqueue->head = NULL;
        myqueue->tail = NULL;

        return p;
    }
    else
    {
        myqueue->queue_len--;

        //remove the head from the queue
        myqueue->head = myqueue->head->prev;
        myqueue->head->next = NULL; //******************Seg Fault here

        p->prev = NULL;

        return p;
        }
}

The error I get when there are two elements is a segmentation fault in line shown, but it works for queues with more. Why wont it let me assign NULL to myqueue->head->next???

A: Change this:
myqueue->head = myqueue->head->prev;
myqueue->head->next = NULL; //******************Seg Fault here

To:
myqueue->head = myqueue->head->prev;
if (myqueue->head != NULL) {
    myqueue->head->next = NULL;
}

It is likely that you are trying to dereference a NULL pointer.  It also would appear that you may have a memory leak from not calling free on the nodes you are deleting, but it is possible you do that elsewhere in the code.


text:
Q: Alternativas similares como Evento Load en MVC Estoy trabajando recién en MVC y quisiera consultar como puedo ejecutar consultas automáticas al abrir una página en mi proyecto MVC 5, algo similar como el PageLoad o Evento Load de .NET.
Gracias.

A: Por el propio concepto de MVC la llamada al controlador se trata como "PageLoad" puesto que llamas al controlador y trabajas allí los datos que quieras antes de mandarlos a la vista y mostrarlos al usuario, luego simplemente tienes que devolver el modelo a la vista o pasar los datos que sean necesarios en el ViewBag, mostrando al usuario el resultado procesado de la vista como deseas después de la carga y procesado de datos. No se si solucionará tu problema.
Un saludo


text:
Q: Parallax Scrolling not working I'm trying to incorporate parallax scrolling to my background where it moves at a slower rate relative to the web page content. I've been following tutorials but nothing is working I am stuck. Here is the jsfiddle - https://jsfiddle.net/batLeeyw/24/
and here is the javascript. Sorry I have a lot of html / CSS so I will leave that in the fiddle link. Also my background image is not showing up in fiddle but it is static when its supposed to parallax in the browser.
function parallax(){
            var para = document.getElementById("parallax-layer");
            para.style.top = -(window.pageYOffset / 4)+"px";
        }

        window.addEventListener("scroll", parallax, false);

A: I'm not sure what your goal exactly is, but try this:
remove:
background-attachment: fixed;

from the #parallax-layer id in the css.
Change your js to:
function parallax(){
         var newtop = (window.pageYOffset / 2);
         $("#parallax-layer").css({top: newtop + 'px'});
         }

window.addEventListener("scroll", parallax, false);

See the result here in the fiddle.
With background-attachment: fixed the image will not move because it is, like the property says, fixed. It's just cutted.
The new js is just a little bit different, I used more jQuery and changed the 4 -> 2. So it scrolls slower than before.
Hope that's what you asked for.

A: You have an error in your CSS syntax, you need to just add http:// before your image url:
background-image: url(http://link);
Working fiddle


text:
Q: Why does this curl command from firefox not download anything? I opened https://raw.githubusercontent.com/andreafrancia/trash-cli/master/README.rst in Firefox, and copy the following curl command from Tools->Web Developer->Network:
curl 'https://raw.githubusercontent.com/andreafrancia/trash-cli/master/README.rst' -H 'Host: raw.githubusercontent.com' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-GB,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1' -H 'If-None-Match: "6931c3b4d0e94743bb93a36ed8e8c3f5add12f9a"' -H 'Cache-Control: max-age=0'

When I run it in lxterminal, it doesn't download anything, even if I add -O to it. I was wondering why it doesn't download, and how I can make it download the file?
Thanks.

A: When debugging curl issues, the -v option is often helpful. In this particular instance, you're running afoul of the If-None-Match header, which tells the server that you already have the file matching "6931c3b4d0e94743bb93a36ed8e8c3f5add12f9a" and that you're not interested in retrieving it again if it hasn't changed. -v shows you this by indicating that the server responds with a 304 header:
< HTTP/1.1 304 Not Modified

To download your file, drop the header:
curl 'https://raw.githubusercontent.com/andreafrancia/trash-cli/master/README.rst' -H 'Host: raw.githubusercontent.com' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-GB,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1' -H 'Cache-Control: max-age=0'

In this particular instance you'll get the same result with
curl 'https://raw.githubusercontent.com/andreafrancia/trash-cli/master/README.rst'


text:
Q: How to write to memory location reserved for struct I have a struct:
struct foo{
  uint8_t i1 : 4;
  uint8_t i2 : 4;
  uint8_t i3 : 4;
  uint8_t i4 : 4;
}

Now, I have a 16-bit integer (call it a) that I want to write to the memory location for this struct, without having to do:
foo1.i1 = (uint8_t)a>>12;
foo1.i2 = (uint8_t)a>>8;
foo1.i3 = (uint8_t)a>>4;
foo1.i4 = (uint8_t)a;

Is there an option to just write the 16 bits to the memory location of foo1. Something like:
*(*uint16_t)&foo1 = a;

A: First of all, you should make sure that this is an optimization that you need to do - done incorrectly, you could run into problems concerning alignment, byte-ordering, etc. As such, you'll want to use a profiler to examine the code performance and determine if this is one of the areas that's consuming a significant amount of processor time. Remember what Donald Knuth wrote:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Once you've confirmed that this is a useful optimization to make, then you should be able to do it in a few ways. One of them is to use memcpy...
memcpy(&foo1, &a, sizeof(foo1));

Alternatively, you could make foo1 a union type with a uint16_t member and write to that...
union {
    struct foo f;
    uint16_t u;
} foo1;
foo1.u = a;


text:
Q: view output stream of a process in addition to my own is it possible to run a process inside my code and then see both output streams (the process and mine) on the screen?
I need to see what the other process doing in parallel with my own code!

A: You need to start a thread which reads data from the Process output stream, and prints it on System.out.
You can use a class like this:
class ProcessOutputStreamPrinter extends Thread {

    BufferedReader reader;

    public ProcessOutputStreamPrinter(Process p) {
        reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    }

    public void run() {
        try {
            String line;
            while (null != (line = reader.readLine()))
                System.out.println("Process output: " + line);
        } catch (IOException e) {
            // handle somehow
        }
    }
}

Here's some test code for that class:
class Test {
    public static void main(String[] args) throws IOException {

        // Start external process. (Replace "cat" with whatever you want.)
        ProcessBuilder pb = new ProcessBuilder("cat");
        Process p = pb.start();

        // Start printing it's output to System.out.
        new ProcessOutputStreamPrinter(p).start();

        // Just for testing:

        // Print something ourselves:
        System.out.println("My program output: hello");

        // Give cat some input (which it will echo as output).
        PrintWriter pw = new PrintWriter(new PrintStream(p.getOutputStream()));
        pw.println("hello");
        pw.flush();

        // Close stdin to terminate "cat".
        pw.close();
    }
}

Output:
My program output: hello
Process output: hello

A: Do the following:

*

*Start a new thread by creating an inner class and extend Runnable

*In the run() method write your code

*Output your code from your block by System.out

*Output the main thread's code by System.out from outside your
block.

The inner class is the most adequate way to initiate a new process (thread). The block I am referring to is your code in the run() method.


text:
Q: onMessage is not called while data only message on ios I am doing fcm integration to flutter demo application.onMessage method is not called when data only message is sent through postman in any condition(forground,background,killed.) (ios physical device iphone5s).
I have tried notification +data message it is working properly.  as described in firebase_messaging plugin.
{
 "to" :"firebase-token",
 "data" : {
     "click_action": "FLUTTER_NOTIFICATION_CLICK",
     "body" : {
        "message":"this is data message"
     },
     "title" : "data title",
     "content_available" : true,
     "priority" : "high"
    }
}

here is content of notification request of postman
 _firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    Fimber.d("onMessage: $message");
    Fluttertoast.showToast(msg: "onMessage: $message",
      toastLength: Toast.LENGTH_LONG
    );
  },
  onLaunch: (Map<String, dynamic> message) async {
    Fimber.d("onLaunch: $message");
    Fluttertoast.showToast(msg: "onLaunch: $message",
        toastLength: Toast.LENGTH_LONG
    );
  },
  onResume: (Map<String, dynamic> message) async {
    Fimber.d("onResume: $message");
    Fluttertoast.showToast(msg: "onResume: $message",
        toastLength: Toast.LENGTH_LONG
    );
  },
);
_firebaseMessaging.requestNotificationPermissions(
    const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered
    .listen((IosNotificationSettings settings) {
  Fimber.d("Settings registered: $settings");
});
_firebaseMessaging.getToken().then((String token) {
  Fimber.d("token: $token");

});

it is in init state of homepage.
 i have permission notifications in ios and working well with notification+data.
-result should be as described in https://pub.dartlang.org/packages/firebase_messaging#-readme-tab-

A: -i have found work around from here
add notification and sound to json like this
{
 "content_available" : true,
 "priority" : "high",
 "to" :"fcm-token",
 "notification":{
        "sound": ""
 },
 "data" : {
   "click_action": "FLUTTER_NOTIFICATION_CLICK",
   "body" : {
        "message":"3:57pm"
   },
  "title" : "data title",
  "content_available" : true,
  "priority" : "normal"
 }
}


text:
Q: Most efficient (speed) way to run hash and filter I have some code that opens a text file and hashes the line. Then filters it by getting the first 4 strings of the hash and opening it as a file. What are some optimization techniques I can use to improve the speed of this script?
Code:
import os
from pathlib import Path
import hashlib
folder_path = "Folder\\"
folder_dir = os.listdir(folder_path)
for folder in folder_dir: # for every folder inside this folder_dir
    for file in os.listdir(folder_path + folder): # for every file inside folder
        r=open(folder_path+folder+"\\"+file,"r+",encoding="ISO-8859-1") # open the file as r
        for line in r: # for every line in r
            if ":" in line: #if the line contains ":", ";", or " ", split the line
                split_line = line.split(":")
            elif ";" in line:
                split_line = line.split(";")
            elif " " in line:
                split_line = line.split(" ")
            else:
                pass
            final_line = split_line[1] # define the split line
            hash = hashlib.md5(final_line.encode('utf-8')).hexdigest() # hash the final_line
            w=open("HashDB\\" + hash[:4] + ".txt","a",encoding="ISO-8859-1").write(hash + ":" + final_line) # open the first 4 letters/numbers of the file and write the hash with the line along with it.

A: If lines only have one of ":; " I'd maybe do this:
def split(line):
  for c in ":; ":
    try:
      return line.split(c)[1], True
    except:
      pass
  return line, False

Multiprocessing:
I'd move all of your code into a function then spawn workers using multiprocessing
So your function looks like this:
def process(input_dir, file):
  with open(os.path.join(input_dir, file),"r+", encoding="ISO-8859-1") as inFile:
    for line in inFile:
      result, processed = split(line)
      if not processed: continue
      hash = hashlib.md5(result.encode('utf-8')).hexdigest()
      with open(os.path.join(HASH_DB, f"{hash[:4]}.txt", "a", encoding="ISO-8859-1") as outFile
        outFile.write(f"{hash}:result")

Spawn the workers:
POOL_COUNT = 10
HASH_DB = "./"

folder_path = "Folder\\"
folder_dir = os.listdir(folder_path)

for folder in folder_dir:
  pool = []
  for file in os.listdir(folder_path + folder):
      if len(pool) == POOL_COUNT:
        for p in pool: p.start()
        for p in pool: p.join()
        pool = []
      pool.append(multiprocessing.Process(target=process, args=(folder, file))

# cleanup if there are any un-run processes
if len(pool):
  for p in pool: p.start()
  for p in pool: p.join()
  pool = []

I haven't tested any of this, but it should be a good starting point


text:
Q: Is there any tool that can monitor status of my working copies from SVN repository? I'm looking for a tool that will alert me (or let me check the status of multiple folders) whenever I have some pending changes in my working copies.
I have multiple projects that I work on and I could really use a tool that would grab my attention in such case.
I know that TortoiseSVN has icon overlays that would do the job if it worked well, but it doesn't.
I tried, and had more issues with TortoiseSVN than before.
I don't want to periodically go through 10+ projects and do TortoiseSVN"s "Check for modifications" manually.
I'm looking for some other solution.
UPDATE:
I might actually be fine with a script.
The key thing is that upon execution I should get a status of multiple working copies.

A: http://www.svnmonitor.com/default.shtml

What is SVN-Monitor?
  Perform all your
  commonly-used svn-actions (update,
  commit, revert, diff ...)
  Keep your
  source up-to-date with minimum
  conflicts and manual merges
  Browse and
  search the svn log from your computer
  while offline (disconnected from the
  svn repository)
   Be constantly aware of
  your local source modifications,
  without using any Visual Studio plugin
  Keep a local updated mirror of the
  repository, while not affecting your
  changes, without the need to commit
  Monitor the source for certain events
  Receive notifications of any kind
  (balloon popups, tray icons, email,
  sounds, ...) when certain events occur

A: Check out the notifier.
http://svnnotifier.tigris.org/

SVN Notifier is a simple and useful tool to monitor your Subversion project repository for changes. SVN Notifier notifies you about recent commits and helps you keep your local copy up to date. You can review all the changes and update your local copy right from the application.


text:
Q: Collection View Cells alpha is changing when it is not supposed to I basically have a collection view where the cells have a view and that view's alpha decreases when the cell is tapped on. For some reason, when I scroll in the collection view, other cells views are also changing alphas and then the original cell that I selected also changed back. It has something to do with the cellForRowAtIndexPath method, but I'm not entirely sure what the issue is. Here is my code:
 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("chooseSpace", forIndexPath: indexPath)as! ChooseSpaceCell

    let space = spaces2[indexPath.row]

    cell.serviceLabel.text = spaces2[indexPath.row]

    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ChooseSpaceCell

    cell.mask.alpha = 0.7
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {

    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ChooseSpaceCell

    cell.mask.alpha = 0.25

}

Originally, all the alphas start out at 0.25, change to 0.7 when tapped, and change back when deselected. This is a huge issue so any help would be much appreciated.

A: When you call
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("chooseSpace", forIndexPath: indexPath)as! ChooseSpaceCell
You are requesting a cell from the collection view. If there is a cell available it will reuse a cell that has already been created. If none are available it creates a new cell.
This means that when you scroll your collection view it is reusing the same cells that you used for previous items. If those items had there opacity changed the new items using that cell will have the same opacity.
You need to add an opacity field to your model or an attribute that will help you compute the opacity.


text:
Q: When using repaint it look like this why? I just want to create a code generator. when a user draws something and then click generate it will show code that you just draw-figture1. But the problem is I using clearscreen-It's boolean to clean the screen. When I draw something it looks likes figure 2 I don't know why?-figture3 for more detail.
package program;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.Array;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Program {

    public static void main(String[] args) {
        Main work = new Main();
        System.out.println("color = "+work.inprogram.color);
        System.out.println("pen = "+work.inprogram.pen);

    }

}
class Main extends JFrame
{
    Inprogram inprogram;
    Main()
    {
        inprogram=new Inprogram();
        setTitle("Tools");
        setSize(1138,743);
        setLocationRelativeTo(null);
        setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        add(inprogram);
        setVisible(true);
    }
}
class Inprogram extends JPanel
{
    DrawSection drawSection;
    String color,pen;
    public Inprogram() {
        setSize(1138,743);
        setLayout(null);
        JLabel tools=new JLabel("Tools");
        tools.setFont(new Font("Comic Sans MS",Font.PLAIN,40));
        add(tools);
        tools.setBounds(60, 52, 187, 61);

        //Bank's section
        JButton pen=new JButton("Pen");
        pen.setBounds(60,159, 151, 48);
        pen.setFont(new Font("Comic Sans MS",Font.PLAIN,35));
        pen.setBorderPainted(false);
        pen.setBackground(Color.WHITE);
        pen.setFocusPainted(false);
        add(pen);
        pen.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent g) {
                //Typo here Back
                //pen=xxxx;
            }
        });

        //Nongnai's section
        JButton color=new JButton("Color");
        color.setBounds(60,300, 151, 48);
        color.setFont(new Font("Comic Sans MS",Font.PLAIN,35));
        color.setBorderPainted(false);
        color.setBackground(Color.WHITE);
        color.setFocusPainted(false);
        add(color);
        color.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent g) {
                //Typo here Nongnai
                //color=xxxx;
            }
        });

        //Jacky's Section
        drawSection=new DrawSection();
        drawSection.setBounds(259, 55, 819, 549);
        add(drawSection);

        //Phum's Section
        JButton generate=new JButton("Generate code");
        generate.setBounds(558,613, 268, 68);
        generate.setFont(new Font("Comic Sans MS",Font.PLAIN,30));
        generate.setBorderPainted(false);
        generate.setBackground(Color.WHITE);
        generate.setFocusPainted(false);
        add(generate);
        generate.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent g) {

            }
        });

    }

}

class DrawSection extends JPanel
{
    int x,y;
    boolean clearscreen=true;
    public DrawSection() {
        setBackground(Color.white);
        setSize(830,575);
        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                x=e.getX();
                y=e.getY();
                repaint();
            }
        });
    }
    @Override
    protected void paintComponent(Graphics g)
    {
        if(clearscreen)
        {
            g.setColor(Color.WHITE);
            g.fillRect(0, 0,830,575);
            clearscreen=false;
        }
        g.setColor(Color.BLACK);
        g.fillOval(x,y,10,10);
    }
}

Figure 1-when does not click anything

Figure 2-when clicked

Figure 3-when clicked

A: there is a mismatch in your components size...
when you create your top container Inprogram you set its size to setSize(830,575); within tis constructor.
later after creation you set its size to drawSection.setBounds(259, 55, 819, 549); and add it into InProgram
this discrepancy leads to the strange effects you see...
Solution:
the most simple way would be to remove the size setting in your InProgram:
//Jacky's Section
drawSection=new DrawSection();
//drawSection.setBounds(259, 55, 819, 549);
add(drawSection);

a better way would be to let the DrawSection determine it's size and draw whatever size it is...
//constructor
public DrawSection() {
    setBackground(Color.white);
    //setSize(830,575); don't set sizer
    addMouseMotionListener(new MouseAdapter() {...});
}
@Override
protected void paintComponent(Graphics g)
{
    if(clearscreen)
    {
        g.setColor(Color.WHITE);
        //g.fillRect(0, 0,830,575);
        g.fillRect(0, 0,getWidth(),getHeight()); //no more hardcoded size
        clearscreen=false;
    }
    g.setColor(Color.BLACK);
    g.fillOval(x,y,10,10);
}


text:
Q: IllegalName: org/hibernate/validator/ValidationMessages I am receiving the following error message in the JBOSS EAP 6.3 server. I am using seam 2.3 and hibernate 4. I am not sure about this issue. com.google.gwt module is giving this error message.
07:59:56,146 WARN  [org.jboss.modules] (http-/127.0.0.1:8080-1) Failed to define class org/hibernate/validator/ValidationMessages in Module "com.google.gwt.gwt-servlet:main" from local module loader @56bbf64f (finder: local module finder @4e27e905 (roots: C:\Software\jboss-eap-6.3\modules,C:\Software\jboss-eap-6.3\modules\system\layers\base)): java.lang.LinkageError: Failed to link org/hibernate/validator/ValidationMessages (Module "com.google.gwt.gwt-servlet:main" from local module loader @56bbf64f (finder: local module finder @4e27e905 (roots: C:\Software\jboss-eap-6.3\modules,C:\Software\jboss-eap-6.3\modules\system\layers\base)))
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:487) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:277) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:92) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.Module.loadModuleClass(Module.java:568) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final-redhat-1]
at java.util.ResourceBundle$Control.newBundle(ResourceBundle.java:2565) [rt.jar:1.7.0_11]
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436) [rt.jar:1.7.0_11]
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400) [rt.jar:1.7.0_11]
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1354) [rt.jar:1.7.0_11]
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296) [rt.jar:1.7.0_11]
at java.util.ResourceBundle.getBundle(ResourceBundle.java:1028) [rt.jar:1.7.0_11]
at org.jboss.seam.core.ResourceLoader.loadBundle(ResourceLoader.java:74) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.core.SeamResourceBundle.loadBundlesForCurrentLocale(SeamResourceBundle.java:99) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.core.SeamResourceBundle.getBundlesForCurrentLocale(SeamResourceBundle.java:78) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.core.SeamResourceBundle.handleGetObject(SeamResourceBundle.java:142) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at java.util.ResourceBundle.getObject(ResourceBundle.java:387) [rt.jar:1.7.0_11]
at java.util.ResourceBundle.getString(ResourceBundle.java:353) [rt.jar:1.7.0_11]
at com.sun.faces.application.resource.ResourceManager.getLocalePrefix(ResourceManager.java:495) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at com.sun.faces.application.resource.ResourceManager.findResource(ResourceManager.java:174) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at com.sun.faces.application.resource.ResourceHandlerImpl.createResource(ResourceHandlerImpl.java:143) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at org.richfaces.resource.ResourceFactoryImpl.createCompiledCSSResource(ResourceFactoryImpl.java:182) [richfaces-core-impl-4.2.0.Final.jar:4.2.0.Final]
at org.richfaces.resource.ResourceFactoryImpl.createDynamicResource(ResourceFactoryImpl.java:466) [richfaces-core-impl-4.2.0.Final.jar:4.2.0.Final]
at org.richfaces.resource.ResourceFactoryImpl.createResource(ResourceFactoryImpl.java:412) [richfaces-core-impl-4.2.0.Final.jar:4.2.0.Final]
at org.richfaces.resource.ResourceHandlerImpl.createResource(ResourceHandlerImpl.java:263) [richfaces-core-impl-4.2.0.Final.jar:4.2.0.Final]
at org.richfaces.resource.ResourceHandlerImpl.createResource(ResourceHandlerImpl.java:273) [richfaces-core-impl-4.2.0.Final.jar:4.2.0.Final]
at com.sun.faces.renderkit.html_basic.StylesheetRenderer.encodeEnd(StylesheetRenderer.java:97) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:877) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1826) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at com.sun.faces.renderkit.html_basic.HeadRenderer.encodeHeadResources(HeadRenderer.java:105) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at com.sun.faces.renderkit.html_basic.HeadRenderer.encodeEnd(HeadRenderer.java:92) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:877) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1826) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1822) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:447) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at org.jboss.seam.jsf.SeamViewHandler.renderView(SeamViewHandler.java:88) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:286) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) [jsf-impl-2.1.28.redhat-3.jar:2.1.28.redhat-3]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) [jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar:2.1.28.Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158) [jboss-seam-2.3.0.Final.jar:2.3.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:231) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:926) [jbossweb-7.4.8.Final-redhat-4.jar:7.4.8.Final-redhat-4]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_11]
Caused by: java.lang.NoClassDefFoundError: IllegalName: org/hibernate/validator/ValidationMessages
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:646) [rt.jar:1.7.0_11]
at java.lang.ClassLoader.defineClass(ClassLoader.java:785) [rt.jar:1.7.0_11]
at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:361) [jboss-modules.jar:1.3.3.Final-redhat-1]
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:482) [jboss-modules.jar:1.3.3.Final-redhat-1]
... 73 more

module.xml
<module xmlns="urn:jboss:module:1.1" name="com.google.gwt.gwt-servlet">
<resources>
    <resource-root path="gwt-servlet-2.4.0.jar"/>
    <!-- Insert resources here -->
</resources>

<dependencies>

</dependencies>
</module>

Anybody have idea regarding this error message?

A: Try adding this dependency in the com.google.gwt.gwt-servlet module.xml:
<dependencies>
    <module name="org.hibernate.validator"/>
</dependencies>


text:
Q: Loop on an object In the internal-transfer-details page, I have a table with two columns: I have a numerical value and a hyperlink.
illustration 1
illustration2
If I click on the first link, I want to retrieve in the HTML table, the value 840.
I get to the internal-transfer-watch page and I get a lot of rows. I just want to retrieve a row. (the value 840)
illustration 3
ID is 347075
illustration 4
The JSON file is here.
internal-transfert-details.component.ts  (parent)
export class InternalTransfertDetailsComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();

  internalTransfertDetails: InternalTransfertDetails[] = [];

  constructor(private service: InternalTransfertDetailsService, private router: Router) { }

  ngOnInit(): void {
    this.getTransfert()
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  private getTransfert(): void {

    this.service.getTransfert().pipe(
      takeUntil(this.unsubscribe$)
    ).subscribe(res => {
      if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {

        this.internalTransfertDetails = res.TRANS.map(
          internalTransfertLine => {
            return {
              titre: {
                label: internalTransfertLine.TITRE.LABEL,
                isin: internalTransfertLine.TITRE.ISIN,
                svm: internalTransfertLine.TITRE.SVM,
              },
              solde: internalTransfertLine.SOLDE,
              qte_vente: internalTransfertLine.QTE_VENTE,
              qte_bloq: internalTransfertLine.QTE_BLOQ,
              qte_trf: internalTransfertLine.QTE_TRF
            }
          }
        );
      }
    });
  }

}

internal-transfert-details.component.html

Transfert Interne - Details

                  Solde

                    {{internalTransfertDetail.solde }}

                      Link

internal-transfert-details.response.ts
import { ApiResponse } from "src/shared/types/api.response";

export interface InternalTransfertDetailsResponse extends ApiResponse {
    TRANS: {
        TITRE: {
            LABEL: string,
            ISIN: string,
            SVM: number,
        },
        SOLDE: number,
        QTE_VENTE: number,
        QTE_BLOQ: number,
        QTE_TRF: number,

    }[];
}

internal-transfert-details.ts
export interface InternalTransfertDetails {
    titre: {
        label: string;
        isin: string;
        svm: number;
    },

    solde: number;
    qte_vente: number;
    qte_bloq: number;
    qte_trf: number;

}

internal-transfert-watch.component.ts  (child)
export class InternalTransfertWatchComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();

  internalTransfertDetails: InternalTransfertDetails[] = [];

  constructor(private service: InternalTransfertDetailsService, private router: Router) { }

  ngOnInit(): void {
    this.getTransfert()
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  private getTransfert(): void {

    this.service.getTransfert().pipe(
      takeUntil(this.unsubscribe$)
    ).subscribe(res => {
      if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {

        this.internalTransfertDetails = res.TRANS.map(
          internalTransfertLine => {
            return {
              titre: {
                label: internalTransfertLine.TITRE.LABEL,
                isin: internalTransfertLine.TITRE.ISIN,
                svm: internalTransfertLine.TITRE.SVM,
              },
              solde: internalTransfertLine.SOLDE,
              qte_vente: internalTransfertLine.QTE_VENTE,
              qte_bloq: internalTransfertLine.QTE_BLOQ,
              qte_trf: internalTransfertLine.QTE_TRF
            }
          }
        );
      }
    });
  }

}

internal-transfert-watch.component.html

Transfert Interne - Details

                  Solde

                    {{internalTransfertDetail.solde }}

Thanks you a lot

A: If you only want one line, don't use ngFor:
Change

  {{internalTransfertDetail[0].solde }}

To

  {{internalTransfertDetails[0].solde }}

A: Modify component.ts by adding filter like below.
this.internalTransfertDetails = res.TRANS.filter(internalTransfert => internalTransfert.SOLDE == param1).map(
      internalTransfertLine => {
        return {
          titre: {
            label: internalTransfertLine.TITRE.LABEL,
            isin: internalTransfertLine.TITRE.ISIN,
            svm: internalTransfertLine.TITRE.SVM,
          },
          solde: internalTransfertLine.SOLDE,
          qte_vente: internalTransfertLine.QTE_VENTE,
          qte_bloq: internalTransfertLine.QTE_BLOQ,
          qte_trf: internalTransfertLine.QTE_TRF
        }
      }
    );

And keep component.html like below.

        {{internalTransfertDetail.solde }}

Hope you got the answer.

A: internalTransfertDetail is an object of an array. There's no reason to use the subscript operator here.

  {{internalTransfertDetail.solde }}

Let me know if this helps ^-^


text:
Q: Download file from third party server and upload to S3 I have a Lambda Node function which is called by a webhook from a thirdparty server. The TP server sends a file download URL and some other data.
The download URL is temporary, so I need to push the file to an S3 for long term storage.
The rudimentary function below, downloads the file and then tries to upload to the S3.
This works when the file is a plain text, but images/pdfs etcs are corrupted when they reach the S3.
const AWS = require("aws-sdk");
const https = require('https');
const path = require('path');

const s3 = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context, callback) => {

  var payload = event.body;
  const url_host = payload.host;
  const url_path = payload.path; //URL of file which needs to be downloaded

  const get_params = {
    host: url_host,
    path: url_path,
    port: 443,
    method: 'GET',
    headers: { }
  };

  var resp = await https_get_processor(get_params); //File downloaded here

  var uploadParams = {
    Bucket: "bucket_name",
    Key: '',
    Body: resp //Preparing to upload the received file
  };

  uploadParams.Key = path.basename(url_path); //Generating filename

  s3.upload (uploadParams, function (err, data) {
    if (err) {
      console.log("Error", err);
    } if (data) {
      console.log("Upload Success", data.Location);
    }
  });

  response = {...} //Generic Response
  return response;
};

async function https_get_processor(get_params)
{
  return await new Promise((resolve, reject) =>
  {
    var data = "";

    const req = https.request(get_params, res => {

      res.on('data', chunk => { data += chunk })

      res.on('end', () =>
      {
        resolve(data);
      })

    });

    req.on('error', (err) => {
      reject(err);
    });

    req.end();
  });
}

A: Response is a Buffer in such case, so try changing request processing by pushing each chunk into an array, and then merge Buffer chunks and pass them.
Try this:
var data = [];

const req = https.request(get_params, res => {

  res.on('data', chunk => data.push(chunk))

  res.on('end', () =>
  {
    resolve(Buffer.concat(data));
  })


text:
Q: How do i count how many words there are, and ignore same words in a string? (using method) The code here only shows how many words they are, how do i ignore the words that are the same?
For example, "A long long time ago, I
can still remember", would return 8 instead of 9.
I want it to be a method which takes one parameter s of
type String and returns an int value. And im only allowed to use the bacics, so no hash keys or hash set and advance stuff.
  public static int mostCommonLetter(String s){

                    int wordCount = 0;

                    boolean word = false;
                    int endOfLine = s.length() - 1;

                    for (int i = 0; i < s.length(); i++) {

                        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
                            word = true;

                        } else if (!Character.isLetter(s.charAt(i)) && word) {
                            wordCount++;
                            word = false;

                        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
                            wordCount++;
                        }
                    }
                    return wordCount;
                }
}

How do i ignore the words that are the same?

A: import java.util.*;

public class MyClass {
    public static void main(String args[]) {
      String input = "A long long time ago, I can still remember";
      String[] words = input.split(" ");
      List<String> uniqueWords = new ArrayList<>();
      for (String word : words) {
        if (!uniqueWords.contains(word)) {
            uniqueWords.add(word);
        }
      }
      System.out.println("Number of unique words: " + uniqueWords.size());
    }
}

Output: Number of unique words: 8
Basically, what you can do if you're allowed to use data structures like lists and so on, is create a list and put the words of the input sentence in the list if and only if they aren't already there.

A: General idea:
public int getUniqueWords(String input) {
    // Split the string into words using the split() method
    String[] words = input.split(" ");

    // Create a Set to store the unique words
    Set<String> uniqueWords = new HashSet<String>();

    // Loop through the words and add them to the Set
    for (String word : words) {
        uniqueWords.add(word);
    }

    // Return unique words amount
    return uniqueWords.size();
}

Same solution using StreamAPI:
public int getUniqueWords2(String input) {
    // here we can safely cast to int, because String can contain at most "max int" chars
    return (int) Arrays.stream(input.split(" ")).distinct().count();
}

If it is needed to handle multiple spaces between words, add some cleanup for input:
// remove leading and trailing spaces
cleanInput = input.trim();

// replace multiple spaces with a single space
cleanInput = cleanInput.replaceAll("\\s+", " ");

Considering the requirement "allowed to use the bacics":

*

*hashtable (HashSet) is a basic data structure in algorithms

*problem of counting unique items cannot be logically solved without a container holding "aready seen" items, so algorithm could check whether the next item is counted or not

*in the role of container in the simplest case could be a list, but that would cause O(n^2) time complexity.

A: You can use a Set<T> collection type, that can only contains unique values:
public static int getTotalUniqueWords(String input) {
    String[] words = input.split(" ");
    Set<String> uniqueWords = new HashSet<>();
    Collections.addAll(uniqueWords, words);
    return uniqueWords.size();
}

or with Streams:
public static long getTotalUniqueWordsStream(String input) {
    String[] words = input.split(" ");
    return Arrays.stream(words).distinct().count();
}


text:
Q: Another word for agnostic when used to suggest independence through a lack of concern As described here, in technical domains agnostic can be used to describe a state of affairs where one thing doesn't care about the specifics of another thing it's related to.  For instance, in software engineering, one might speaking of a "platform-agnostic" solution.  This suggests that the solution need not have any information about the platform it is executing on to be a solution - it's a solution independent of the platform.  In the same way you can talk about things being "OS-agnostic" or "language-agnostic".
I'm suffering tip of the tongue phenomenon.  I think that there's another word that be used in these "X-agnostic" constructions that means specifically what agnostic is being used for here.  When I try to sound it out, however, my brain keeps jumping back to "agnostic" or to "ambivalent", which is also not the word I'm thinking of.
I think the word I'm thinking of can also be used to describe the relationship between a theory and a question if the theory is non-dispositional with regard to the answer to the question.  "My theory is X with regard to that question."
It's driving me crazy.  What's the word I'm thinking of?

A: A term synonymous with platform-agnostic is platform-neutral.
Perhaps the word you're thinking of is neutral.

A: You might also try:

independent : not dependent; not depending or contingent upon something else for existence, operation, etc. .

The abstraction layer is OS-independent.

A: apathetic?
indifferent?
blind?

A: I'd go with apathetic.
To help illustrate the nuanced difference between apathetic and agnostic, I present you with The Church of the Apathetic  Agnostic ("We don't know, and we don't care")

A: You could say platform promiscuous

not restricted to one class, sort, or person : indiscriminate - education … cheapened through the promiscuous distribution of diplomas — Norman Cousins

A: Platform-independent
Platform-independent is the term I know from having worked in Information Technology. It means that a solution will work across multiple platforms - ie is not 'dependent on any particular platform' - in order to work.
I'm putting it as an answer as 'independent' is only half the answer and 'platform-independent' appears only in a comment.
https://en.m.wikipedia.org/wiki/Platform-independent_model


text:
Q: How to enable multiple input text fields with one checkbox with jquery? I have multiple text fields that is disabled by default and I have one checkbox above them. I want that when you check this checkbox it will enable all text fields.
**Checkbox** not checked            **Checkbox** checked
**input field** disabled            **input field** enabled
**input field** disabled            **input field** enabled
**input field** disabled            **input field** enabled
**input field** disabled            **input field** enabled
**input field** disabled            **input field** enabled
etc....

It need to fit this html structure:

   <input type="checkbox" id="checkbox">co-applicant

      <input type="text" id="inputbox" required pattern="[a-zA-Z]+" placeholder="First name" disabled="disabled">

     <input type="text" id="inputbox" required pattern="[a-zA-Z]+" placeholder="Last name" disabled="disabled">

     <input type="email" id="inputbox" required placeholder="Email" disabled="disabled">

I have looked up several examples but didn't get any of them to work. Also, the jquery code - where should I put it for it to work the best?
Thanks for the help!

A: $('#test').click(function() {
    $('input:text').attr('disabled',!(this.checked))
});

Demo1
Update for Email type:
In case if you are using different type',Select with input
$('#test').click(function() {
    $('input').attr('disabled',!(this.checked))
});

Demo2

A: $('#checkbox').click(function() {
        $(".inputbox").prop("disabled",false);

});

"inputbox" is make it as class.
DEMO

A: $('#checkbox').click(function() {
        $("input:text").prop("disabled",false);
});

A: You must have unique ID's. You can change all your multiple IDs to Classes instead.
Try this:
$('#checkbox').on('change', function() {
    if (this.checked) {
        $(this).closest('div').find('input').removeAttr("disabled");
    }
});

Demo here
Or, if you want to go by class (by changing your ID's to Class like in my demo under):
$('#checkbox').on('change', function() {
    if (this.checked) {
        $(this).closest('div').find('.inputbox').removeAttr("disabled");
    }
});

Demo here

A: Solved it! Changed the input id to be a class instead.

   <input type="checkbox" id="checkbox">co-applicant

      <input type="text" class="inputbox" required pattern="[a-zA-Z]+" placeholder="First name" disabled="disabled">

     <input type="text" class="inputbox" required pattern="[a-zA-Z]+" placeholder="Last name" disabled="disabled">

     <input type="email" class="inputbox" required placeholder="Email" disabled="disabled">

And the jquery:


text:
Q: Unable to send Post Request on Google Apps Script I am trying to send a post request to verify a transaction. I sent the same post request with Postman and I got a response as shown below:

Apps Script Code.gs:
function postRequest() {
    var url = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify";
    var options = {
        "method": "post",
        "headers": {
            "Content-Type": "application/json"
        },
        "payload": {
            "SECKEY": "FLWSECK-e6db11d1f8a6208de8cb2f94e293450e-X",
            "txref": "MC-1520443531487"
        }
    };

    const response = UrlFetchApp.fetch(url, options);

    Logger.log(JSON.stringify(response));
}

Apps Script Error Response:

Request failed for
  https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify
  returned code 400.
Truncated server response: SyntaxError: Unexpected token S
   at parse
  (/app/node_modules/body-parser/lib/types/json.js:83:15)
   at /app/node_mod... (use muteHttpExceptions option to examine
  full response) (line 299, file "Code")

What am I doing wrong or How do I send a post request in Google Apps Script?

A: The UrlFetchApp.fetch() function has an unusual quirk in that you have to use the contentType property to set the content type of the payload. For some reason, setting the header directly doesn't seem to work.
In addition you need to JSON.stringify() your payload.
So rewrite your post request as follows:
function verify() {
    var url = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify";

    var options = {
        "method":"POST",
        "contentType":"application/json",
        "payload":JSON.stringify({
            "SECKEY":"[YOUR-SECRET-KEY]",
            "txref":"[YOUR-TXREF-CODE]"
        })
    };

    return JSON.parse(UrlFetchApp.fetch(url, options));
}

Note that I omitted the key and code with placeholder text. You really shouldn't share that kind of sensitive information. If possible I strongly recommend revoking those keys and have the service vendor issue new ones.

A: This is not a problem with Google Apps Script but the flutterwave server is returning a 400 error code.
You can check this by adding "muteHttpExceptions": true to the options object and then logging the response in the console.
function postRequest1() {
    var url = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify";
    var options = {
        "method": "post",
        "headers": {
            "Content-Type": "application/json"
        },
        "payload": {
            "SECKEY": "FLWSECK-e6db11d1f8a6208de8cb2f94e293450e-X",
            "txref": "MC-1520443531487"
        },
        "muteHttpExceptions": true
    };

    const response = UrlFetchApp.fetch(url, options);
Logger.log(response.getResponseCode())
Logger.log(response.getContentText())
}

A: Thanks to Dimu Designs for explaining a quirk of UrlFetchApp.fetch()
All I did to make it work was to change Content-Type to contentType
function postRequest() {
    var url = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify";
    var options = {
        "method": "post",
        "headers": {
            "contentType": "application/json" // <--  HERE
        },
        "payload": {
            "SECKEY": "FLWSECK-e6db11d1f8a6208de8cb2f94e293450e-X",
            "txref": "MC-1520443531487"
        },
        "muteHttpExceptions": true
    };

    const response = UrlFetchApp.fetch(url, options);

    Logger.log(response.getContentText());
    Logger.log('Response Code: '+response.getResponseCode())
}

On the other hand "muteHttpExceptions": true is there so that I will handle the Http exceptions myself.


text:
Q: Can't get serialize data in a Modal I have some modal like this:

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

        <form id="categoryForm" class="form-horizontal" data-toggle="validator">
            {{ csrf_field() }}
            {{ method_field('POST') }}

                <input type="hidden" name="id" id="id">

                        Category

                            <input class="form-control" id="name" name="name" placeholder="Category name" required autofocus>

                        Slug

                            <input class="form-control" id="slug" name="slug" placeholder="Category slug" required>

                        Description

                            <textarea class="form-control" id="description" name="description" rows="5"></textarea>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>

        </form>

i try to run an ajax so i try to catct the event when submit button is pressed so i do like this:
       $('#categoryForm form').validator().on('submit', function( event ) {
            alert('all ok')
       }

but it seem i can't trigger the event. instead i have to do it like this:
        $(document).validator().on('submit', function( event ) {
            alert('all ok)
        }

can anyone telling me what going on? since i try to serialize the data for my ajax like this:
if (!event.isDefaultPrevented()){
                   event.preventDefault();
                   var id = $('#id').val();
                   if (save_method === 'add') url = "{{ route('category.index') }}";
                   else url = "{{ route('category.index'). '/' }}"  +  id;
                   alert($('#categoryForm form').serialize());
                   $.ajax({
                       url: url,
                       type: 'POST',
                       data: $('#categoryForm form').serialize(),
                       success: function ( data ) {
                           $('#categoryForm form').modal('hide');
                           table.ajax.reload()
                       },
                       error: function (data ) {
                           alert('something is not right');
                       },
                       statusCode: {
                           404: function() {
                               alert( "page not found" );
                           },
                           405: function (  ) {
                               alert('Method not allowed')
                           }
                       }
                   })

it fail and give me Method not allowed. i think it's because i don't get any data from serialize since when i try to alert it i got nothing. Thank.s


text:
Q: Downloading/storing Periscope live streaming broadcasts I'm crawling tweets and, if available, store information to external resources (e.g., Instagram images). Now poeple start using Periscope where users tweet links to a Periscope live streaming broadcast (also then available for the next 24h). Here is an example link, but it might be invalid/obsolete soon.
Is there any way I can fetch that broadcast, i.e., store it locally as a video file?
When I look at the source code of a Periscope broadcast, I get something like that:

  ...

So everything is essentially scripted. I've tried to look into the Javascript file to see if I can somehow at least reconstruct the stream URL or something. But I wasn't successful. I also tried with Google Chrome to inspect the requests made from the side. But this also didn't bring me any further.
EDIT: Here's my current Phantom.js script:
var page = require('webpage').create(),
  system = require('system'),
  t, address;

if (system.args.length === 1) {
  console.log('Usage: periscope.js <periscope-url>');
  phantom.exit();
}

page.onResourceRequested = function(request) {
  console.log('Request ' + JSON.stringify(request, undefined, 4));
};

page.onResourceReceived = function(response) {
  console.log('Receive ' + JSON.stringify(response, undefined, 4));
};

address = system.args[1];

page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36';
page.open(address, function(status) {
  if (status !== 'success') {
    console.log('FAIL to load the address');
  } else {

  }
  //phantom.exit();
});

When I use Google Chrome's Developer Tools I find the application/vnd.apple.mpegurl request, but it never pops up from the Phantom.js script.

A: It uses Http Live Streaming (HLS) on Chrome Desktop so just proxy/sniff HTTP responses of type application/vnd.apple.mpegurl and get the request URL. I was able to watch your stream in VLC.
You can use Phantom.js.

A: the latest version of the fantastic livestreamer (1.12.2) can download periscope videos
livestreamer https://www.periscope.tv/w/aKzPpDIxNDYxN3w2OTg1MTQxNZnjGACxw2Nyl6RSvdnX8T3EaE7z5mSvxfK_-uqS5SQv best --output output.mp4

if you want to do it programmatically seeing as this is StackOverflow, the periscope plugin in python is here:
https://github.com/chrippa/livestreamer/blob/develop/src/livestreamer/plugins/periscope.py


text:
Q: How to compare type while scripting in abaqus with python I'm trying to compare type of abaqus object, but it doesn't work. An idea ?
>>> m = mdb.models['Model-1']
>>> type(m)
<type 'Model'>
>>> type(m) == Model
NameError: name 'Model' is not defined

I want those type of comparison or many other object, not only Model
I tried :
>>> import Model
ImportError: No module named Model
>>> type(m) == mdb.models.Model
AttributeError: 'Repository' object has no attribute 'Model'

A: It is easy to confirm the Python's built-in data type, because as they are built-in, we don't need to import them. For ex.
a = []
type(a) == list  # similar for other built-in python data types

However, Abaqus data types are not built-in. Hence, we must import then from respective modules to compare them. Following is the example for Model and Part data types.
# importing the modules
import abaqus as ab  # just for demonstation I'm importing it this way
import part as prt

# accessing the model and part objects
myModel = ab.mdb.models['Model-1']
myPart = myModel.parts['Part-1']

#checking the data types
type(myModel) == ab.ModelType  # Model is imported from Abaqus module
type(myPart) == prt.PartType   # Part is imported from Part module

# you can use 'isinstance()' method also
isinstance(myModel, ab.ModelType)  # Model is imported from Abaqus module
isinstance(myPart, prt.PartType)   # Part is imported from Part module


text:
Q: Does HP webOS have a WYSWYG GUI design tool? I hope to migrate one of my apps to HP webOS.  Does webOS have WYSIWYG GUI tool that integrates with Mojo or Enyo, or do have to use a HTML/CSS/JavaScript editor?

A: There is a WYSIWYG editor for Mojo apps called Ares.  You can check it out at: https://ares.palm.com/Ares/login.html
You'll need to set up a developer account first.  It has been reported that Ares will be updated to support Enyo.  When working with Enyo apps (or Mojo apps for that matter) you can use pretty much any environment/IDE that you prefer.

A: The other two pretty decent options are Eclipse and JetBrains WebStorm. Both have fairly decent Mojo plugins, though I have been unimpressed by their Enyo offerings to date.


text:
Q: Pass attribute value to view from controller in angularjs I have a  tag with the following things:

I'm calling a REST API. After calling REST API, I get the values of src, height and width. How can I pass from controller to view in angularjs?

A: Yes.
To controll the src you need to use ngSrc directive:

To controll the style use ngStyle directive:
$scope.myStyle = {"width":"500px", "height":"500px"};


text:
Q: Make text disappear after user input Is there a way you can make the displayed content disappear just after user gives input ?
For example, take this file below
#!/bin/bash
read -n 1 -p 'how are you ? ' var
if [ "$var" == "y" ]
then
    echo 'Have fun'
else
    echo 'Go to Doctor'
fi

If you run this, the output is
how are you ? yHave fun

I am looking for something that let me make how are you ? disappear as soon as user presses a key
And then after disappearing, print Have fun
So, I want the last output of the above program to be only
Have fun

Note: Also, anything above this script that is printed on the shell screen should not be erased.
I am using bash

A: There are a number of ways to do this, ranging from idiot proof to elegant.
The most foolproof method (although the most work) is backspace space backspace repeated however many times needed. This works on everything but teletypes (removing ink from paper is a challenge).
Next up the scale is carriage return spaces carriage return. This does not work with terminal emulators that insert a linefeed before or after each carriage return (this is an option minicom and others may be configured to have).
Then there is the terminal specific tricks I will mention  only termcap capability codes as termcap and terminfo databases can show usage. (Here is a list.)
Simple for a single line is move to column (ch) followed by clear to end of line (ce).
For more complicated cases including multi line responses there is save absolute position (sc), prompt, read response, restore cursor position (rc), clear to end of screen (cd).
In most cases you can hardcode the vt100 values for the last two answers as most terminal emulators are compatible with it. Of course not all terminals support those options, but those that don't are rare and obsolete.

A: Use a carriage return (\r). This special character (a leftover from the days of mechanical typewriters) will move the cursor back to the beginning of the line. Then, you need as many spaces as the message you want to delete (this will overwrite the message) and then a second carriage return to go back to the beginning before printing the next message. Something like this:
#!/bin/bash
echo foo
read -n 1 -p 'how are you ? ' var
if [ "$var" == "y" ]
then
    printf '\r                \rHave fun\n'
else
    printf '\r                \rGo to Doctor\n'
fi

Running the script above prints:
$ foo.sh
foo
Have fun

A: You can use:
tput cr

(or printf '\r') to move the cursor to the beginning of the line. Followed by:
tput el

to delete everything up to the end of the line. (tcsh and zsh also have the echotc builtin which you can use with the termcap equivalent of that terminfo el: echotc ce (also echoti el in zsh))