text:
Q: Directly grouping rows from pandas.DataFrame through matplotlib plotting I have a Dataframe saved as a .csv file that is similar to the one produced by the following code:

dates = [["2022-03-31", "A",100], ["2022-03-31", "B",100],  ["2022-03-31", "C", 250], ["2022-04-31", "A", 500], ["2022-04-31", "B", 100], ["2022-04-31", "C", 200], ["2022-05-31", "A",200], ["2022-05-31", "B", 300], ["2022-05-31", "C", 500]]

df = pd.DataFrame(dates, columns=['Dates',"Payment Method", "Values"])

df.to_csv("example.csv",index=False)

What I am trying to do is to set each month of the year (in the "Dates" column) as a singular x axis tick using matplotlib.pyplot and create a line for each payment method ("Payment Method" column)  with its corresponding values ("Values" column) on the y axis for each month on the x axis. So for the payment method a
How would I go about directly grouping the months in the "Dates" row and plot 3 different lines (for payment methods "A", "B" and "C") with their corresponding values for each month using pandas and matplotlib?

A: Here are two solutions. The first is using pandas only. Pandas makes it easy to plot data and the backend is matplotlib, too. The second solution uses matplotlib.
Data handling
Before I start, I want to comment, that I don't use [pd.groupby()], because in this case df.pivot() is more useful and brings your DataFrame into a nice shape like this
dates = [["2022-03-31", "A",100], ["2022-03-31", "B",100],  ["2022-03-31", "C", 250], ["2022-04-31", "A", 500], ["2022-04-31", "B", 100], ["2022-04-31", "C", 200], ["2022-05-31", "A",200], ["2022-05-31", "B", 300], ["2022-05-31", "C", 500]]
df = pd.DataFrame(dates, columns=['Dates',"Payment Method", "Values"])
df['Dates'] = df['Dates'].str[:7]
df_pivot = df.pivot('Dates', 'Payment Method', 'Values')

>>> df_pivot
Payment Method    A    B    C
Dates
2022-03         100  100  250
2022-04         500  100  200
2022-05         200  300  500

which is easy to plot for both solutions.
As long you dates are of type string, you could replace() or slice the strings to remove the days.
In gerneral I suggest to parse dates to a datetime object using pd.to_datetime().
df['Dates'] = pd.to_datetime(df['Dates'])
df['Dates'] = df['Dates'].dt.strftime('%Y-%m')

but this gives you an error, because "2022-04-31" is not a valid date. Maybe this is something you should think about.
Pandas plot
fig = df_pivot .plot.bar()

The fig variable is of type matplotlib.axes._subplots.AxesSubplot. As you can see, pandas uses matplotlib and if you want to make changes to this figure, this is still possible afterwards. I think there is no need to use plain matplotlib.

I am not sure if your want a bar plot, but you can switch to df_pivot.plot.line() or other methods, too.
Matplotlib
This solution is pretty much based on the matplotlib barplot example.
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(len(df_pivot))
width = 0.2 # the width of the bars

fig, ax = plt.subplots()

rects1 = ax.bar(x - width, df_pivot['A'], width, label='A')
rects2 = ax.bar(x, df_pivot['B'], width, label='B')
rects2 = ax.bar(x + width, df_pivot['C'], width, label='C')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Value')
ax.set_title('Value by group and date')
ax.set_xticks(x, df.index)
ax.legend()

plt.show()

As you can see, this needs some more lines of code.


text:
Q: Save bitmap image to specific location of gallery android 10 I am using this code:
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title" , "description");

and it is working well.
Problems:

*

*It is creating a folder called "Pictures" in gallery automatically. But I want different name, for example my app's name.

*insertImage() function of MediaStore is depreciated in android 10:

public static String insertImage (ContentResolver cr,
String imagePath,
String name,
String description)

This method was deprecated in API level 29.
inserting of images should be performed using MediaColumns#IS_PENDING, which offers richer control over lifecycle.

I have read the documentation and don't actually understand IS_PENDING and how to use it.

A: Try this code :-
private void saveImage(Bitmap bitmap, @NonNull String name) throws IOException {
    boolean saved;
    OutputStream fos;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ContentResolver resolver = mContext.getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        fos = resolver.openOutputStream(imageUri);
    } else {
        String imagesDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;

        File file = new File(imagesDir);

        if (!file.exists()) {
            file.mkdir();
        }

        File image = new File(imagesDir, name + ".png");
        fos = new FileOutputStream(image);

    }

    saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filler word for SQLite statement to return any and all rows using WHERE I am trying to make a Flask web app to search an SQLite database of people (for the sake of example). The user can give as many parameters as they want: eg give the firstname and the age but don't specify their location (with the same names for these variables). However when I run the query in the background and insert the user specified values into the SQLite statement I don't have anything to write as the condition for the latter (location). Is there a "filler" text which just gives any result from those columns?
db.execute = ("SELECT * FROM people WHERE firstname = ? AND age = ? AND location = ?", firstname, age, location)

<- since the user did not specify the location this last variable is 'empty'.
I am thinking of an
if

branch to see if the user specified a condition for each column. If they did not, what phrase could I use? How can I make SQLite to return all rows which satisfy the known conditions (firstname and age), regardless of the location?
I tried leaving the value empty, which resulted in an error message (not sufficient parameters). I tried to set the variable to None, again errored.


text:
Q: Convert date to julian I am trying to convert a date into a julian date. I have this data frame
      diff   yr mo dy hr
1 3.174583 1873 12  1  1
2 2.874583 1873 12  1  3
3 2.574583 1873 12  1  5
4 2.074583 1873 12  1  7
5 1.774583 1873 12  1  9
6 1.474583 1873 12  1 11

and for every row I want to assign the number of days since a particular date (e.g. "1870-01-01").
I tried like this
julian(as.Date(paste(dep$yr,dep$mo,dep$dy,sep="/"),"%Y/%m/%d"))

but this gives me the days since "1970-01-01".. If I try to set the origin
  julian(as.Date(paste(dep$yr,dep$mo,dep$dy,sep="/"),"%Y/%m/%d"),origin = paste(1870,1,1,sep="-"))

then I get this error
Error in unclass(x) - unclass(origin) :
  non-numeric argument to binary operator

Can some one help me?
Many thanks

A: Using ISOdate here and a proper origin date value should help you
julian(with(dep, ISOdate(yr,mo,dy,hr)), origin=as.Date("1870-1-1"))

# Time differences in days
# [1] 1430.042 1430.125 1430.208 1430.292 1430.375 1430.458


text:
Q: How can i install development libraries for 'icu-le' and 'icu-uc'? I get this when I try to compile 'harfbuzz'.
No package 'icu-le' found
No package 'icu-uc' found

i have tried 'sudo apt-get install libicu-uc. But that does not solve the problem.

A: If all you need are the development libraries, try installing libicu-dev and if you need the actual library, the name is libicu48.
apt-cache search libicu

This did the trick.
So:
sudo apt-get install libicu-dev


text:
Q: How to accelerate (parallelize ?) a text file editing? I have a script that delete the second line if it has a certain pattern. However when ran on a folder that contains hundreds of files it is pretty slow, I have to wait 5 minutes or so for it to complete. Since it's i/o I'm sure there is a way to accelerate or parallelize it do you know how ? Here is the current slow code :
import datetime as dt
import os, re

for symb in os.listdir(r'C:\folder'):

    n1=dt.datetime.now()

    fh, abs_path = mkstemp()

    new_file = open(abs_path,'w')

    file_path = r'C:\folder' + '\\' + symb

    print(repr(file_path))

    old_file = open(file_path, 'r')
    new_file = open(abs_path, 'w')

    data = old_file.readlines()

    if re.match('9:', data[1]):
        print('YES')
        del data[1]

    for line in data :
        new_file.write(line)

    new_file.close()
    close(fh)
    old_file.close()

    remove(file_path)

    move(abs_path, file_path)

    print(symb + ' : ' + str((dt.datetime.now()-n1).microseconds))

A: You are likely disk bound, but you could tighten up the code a bit by doing larger block copies. Instead of readlines/writelines, process the first two lines manually and then turn it over to shutil for the rest.
import shutil

....

    line1 = oldfile.readline()
    line2 = oldfile.readline()
    if re.match('9:', line2):
        line2 = ''
    newfile.write(line1 + line2)
    shutil.copyfileobj(old_file, new_file, length=1024*1024)

You could see if you are disk bound by doing an xcopy of all the files and seeing if the time is about the same. if you have multiple hard drive, you should make sure that the intermediate file is on the same drive.

A: Take a look into the multiprocessing module. For example, you could use Pool to map a function over the list of files in parallel:
from multiprocessing import Pool
p = Pool(5)
def doIt(x):
    # do the thing

p.map(doIt, os.listdir(r'C:\folder'))


text:
Q: Duplicate variable creation in JavaScript - Is it problematic? I've noticed Photoshop's ScriptListener code kick out a duplicate line.
    var idChnl = charIDToTypeID( "Chnl" );
    var idChnl = charIDToTypeID( "Chnl" );

This ScriptListener bug aside, my question is this: Is it problematic, when a variable in a script, (such as idChnl), is created twice?

A: The second variable assignment (or if more than two variable assignments, the last variable assignment) will overwrite the initial assignment(s) as seen in this example:

var a = "Hello";
var a = "World";

alert(a);

With regards to problems with this, code readability and confusion with code maintenance in the long run are a few of the problems I could think of.


text:
Q: Method to generate error (failure) for a SwiftUI Combine publisher I'm writing a Mock service to test login in a SwiftUI MVVM project. In my ViewModel:
  func login() {
    self.cancellable = service.login(email: email, password: password)
      .sink(receiveCompletion: { [weak self] completion in
        switch completion {
          case .finished:
            break
          case .failure(let error):
            if let session = self?.session {
              session.currentUser = nil
            }
            print(error.localizedDescription)
        }
      }, receiveValue: { user in
        if let session = self.session {
          session.currentUser = user
        }
      })
  }

My mock service code:
func login(email: String, password: String) -> AnyPublisher<User, Error> {

    let user = User(name: "test", email: email, password: password)
    if email.lowercased() == "test@mail.com" && password == "Password!23" {
      return Just(user)
        .setFailureType(to: Error.self)
        .eraseToAnyPublisher()
    } else {
      // ??? How to generate a failure here
    }
  }

My question is how to generate an error (failure) in my code? I only found some code sample regarding with error handling. But can't find how to generate an error in publisher.

A: There's an Fail Combine publisher that does exactly what you're after:
extension String: Error {}

func randomlyFail() -> AnyPublisher<Int, Error> {
   Bool.random()
    ? Fail(error: "random error")
        .eraseToAnyPublisher()
    : Just(1)
        .setFailureType(to: Error.self)
        .eraseToAnyPublisher()
}


text:
Q: Get value from xarray format in python I try to get data from netCDF format with xarray
I have code like this,
import numpy as np
import pandas as pd
import xarray as xr
import sys, json
import base64

ds = xr.open_dataset('/home/misdan/Documents/Data/Angin/wind_1992.nc')
da = ds['u10'].sel(time='1992-02',latitude=6.0, longitude=95.20,method='nearest').data

print('--------------------------')
print('hasilnya adalah : ')
print(da)

The result is like this
hasilnya adalah :
[-2.2909293]

how i can get the value from the result without [], like this
hasilnya adalah :
-2.2909293

the data is like this
<xarray.DataArray 'u10' (time: 1)>
array([-2.290929], dtype=float32)
Coordinates:
    longitude  float32 95.25
    latitude   float32 6.0
  * time       (time) datetime64[ns] 1992-02-01
Attributes:
    units:      m s**-1
    long_name:  10 metre U wind component

A: print(da[0]) will print the first item in the da list, which is what you are looking for.


text:
Q: Why doesn't my code enter for loop when record found? I have an object(Huishouden__c) with a related list. I loop trough the object records with a for loop on the related record. When I debug the object in the first loop I get an Id but it does not enter the second loop?
[SELECT id FROM Huishouden__c WHERE id IN : uniqueHuish]

This returns an Id, I doent see any errors in my debug
Loops:
 List<Huishouden__c> deleteHuish = new List<Huishouden__c>();
    for(Huishouden__c h: [SELECT id FROM Huishouden__c
                          WHERE id IN : uniqueHuish]) {
                              system.debug('SELECT id FROM Huishouden__c'+ [SELECT id FROM Huishouden__c WHERE id IN : uniqueHuish]);
                              for(Relatie__c rc : h.Relatie_Contacten__r) {
                                  system.debug('h'+h);
                                   system.debug('h.Relatie_Contacten__r'+h.Relatie_Contacten__r);
                                  if(h.Relatie_Contacten__r.size()<=1) {
                                      deleteHuish.add(h);
                                  }
                              }
                          }
    delete deleteHuish;
    system.debug('deleteHuish '+deleteHuish);

A: According to your code, you need to execute a SOQL to fetch the child records which you are not doing currently. Thats why it is not entering inner for loop.
Since, you are checking the count and trying to delete records, you can follow this most optimized approach.
Prepare an Aggregate query like this and execute the delete operation. Be sure to verify the related parent field (e.g. Huishouden__c ) from child object Relatie__c based on which you will be grouping the records.
List<Huishouden__c> deleteHuish = new List<Huishouden__c>();
List<AggregateResult> results = [SELECT Huishouden__c, COUNT(Id) idCount
                                    FROM Relatie__c
                                    WHERE Huishouden__c IN:uniqueHuish
                                    GROUP BY Huishouden__c
                                    HAVING COUNT(Id) <2];

for(AggregateResult result: results)
{
    Huishouden__c obj = new Huishouden__c(Id = (String) result.get('Huishouden__c'));
    deleteHuish.add(obj);
}
delete deleteHuish;


text:
Q: Flutter firebase logged in user returns a NULL currentUser after sign in When authenticating in firebase using the signInWithEmailAndPassword() API, I am unable to get a valid "current" user.

*

*I sign into the application with user name and password

auth.signInWithEmailAndPassword()

*I once signed in the user is taken to a Home page

*I attempt to get the user's UID but there is no valid user returned. The call happens in an async function as such:
currentUser = await auth.currentUser();

currentUser is null.
Any ideas what could be causing this?

A: The documentation suggests that you use an auth state observer to get a callback when the user is signed in and a User object is available.  As shown in that linked documentation:
FirebaseAuth.instance
  .authStateChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

I strongly suggest not relying on currentUser, as that can only check at a moment in time.  The observer is guaranteed to let you know when the user object is available for use.

A: What if you reload the returned FirebaseUser? This worked for me.
const User currentUser = await auth.currentUser;
if (currentUser != null) {
  await currentUser.reload();
}

Clearly simplified code. Note: auth.currentUser() is now auth.currentUser.
This might be a duplicate: Flutter Firebase Authentication currentUser() returns null.

A: after getting user just reload it once it will solve your problem
code for reference :D
final FirebaseAuth _auth = FirebaseAuth.instance;
  User currentuser;
  bool isloggedin= false;
  getUser() async{

    User user =  _auth.currentUser;
    await user?.reload();
    user =  _auth.currentUser;

    if(user !=null)
    {
      setState(() {
        this.currentuser = user;
        this.isloggedin=true;
      });
    }
  }


text:
Q: Binding ObservableCollection contained in ViewModel to ListView I've searched and searched but can't obtain a proper, helpful answer.
I have a MainWindow wpf window. Its DataContext is set to its ViewModel.
I have a ListView which is binded to an ObservableCollection in the ViewModel:
        <ListView Grid.Row="1" Grid.Column="0" Margin="2" Name="sources_ListView" Grid.RowSpan="1" ItemsSource="{Binding Path=Sources}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="290" Header="Name"
                                    DisplayMemberBinding="{Binding Path=OriginalPath}"/>
                    <GridViewColumn Width="80" Header="Type"
                                    DisplayMemberBinding="{Binding Path=Type}"/>
                </GridView>
            </ListView.View>
        </ListView>

RelayCommand:
        public ICommand BrowseFileFolderCommand
        {
            get
            {
                if (_browseFileFolderCommand == null)
                {
                    _browseFileFolderCommand = new RelayCommand(o =>
                               {
                                  _sources.Add(new SourceItem(selectedPath, new DirectoryInfo(selectedPath)));
                               }, null);
                }
                return _browseFileFolderCommand;
            }
        }

Now obviously what the Lambda function does, wouldn't work in the real world as I have taken it out of context, but accept the fact that it does add SourceItem to the ObservableCollection _sources and that there is a Public Sources which gets the _sources. I have also made the type that ObservableCollection takes use INotifyChangedProperty.
When I use that RelayCommand which is inside a button which adds a source to the ObservableCollection, the ListView doesn't update?
Thanks for any help
EDIT SourceItem:
public class SourceItem : ISourceItem, INotifyPropertyChanged
{
    DirectoryInfo _sourceFolder;
    public DirectoryInfo SourceFolder { get { return _sourceFolder; } private set { _sourceFolder = value; } }

    FileInfo _sourceFile;
    public FileInfo SourceFiles { get { return _sourceFile; } private set { _sourceFile = value; } }

    string _originalPath;
    public string OriginalPath { get { return _originalPath; } private set { _originalPath = value; OnPropertyChanged("OriginalPath"); } }

    bool _isFolder;
    public bool IsFolder { get { return _isFolder; } }

    // display friendly property of IsFolder
    public string Type { get { return _isFolder == true ? "Folder" : "File"; } }

    public SourceItem(string originalPath, DirectoryInfo sourceFolder)
    {
        _originalPath = originalPath;
        _sourceFolder = sourceFolder;
        _sourceFile = null;

        _isFolder = true;
    }

    public SourceItem(string originalPath, FileInfo sourceFile)
    {
        _originalPath = originalPath;
        _sourceFile = sourceFile;
        _sourceFolder = null;

        _isFolder = false;
    }

    #region INotifyPropertyChanged Members

    /// <summary>
    /// Raised when a property on this object has a new value.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Raises this object's PropertyChanged event.
    /// </summary>
    /// <param name="propertyName">The property that has a new value.</param>
    protected virtual void OnPropertyChanged(string propertyName)
    {
        this.VerifyPropertyName(propertyName);

        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    #endregion // INotifyPropertyChanged Members

    #region Debugging Aides

    /// <summary>
    /// Warns the developer if this object does not have
    /// a public property with the specified name. This
    /// method does not exist in a Release build.
    /// </summary>
    [Conditional("DEBUG")]
    [DebuggerStepThrough]
    public void VerifyPropertyName(string propertyName)
    {
        // Verify that the property name matches a real.
        // public, instance property on this object
        if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        {
            string msg = String.Format("Invalid property name: {0}", propertyName);

            if (this.ThrowOnInvalidPropertyName)
                throw new Exception(msg);
            else
                Debug.Fail(msg);
        }
    }

    /// <summary>
    /// Returns whether an exception is thrown, or if a Debug.Fail() is used
    /// when an invalid property name is passed to the VerifyPropertyName method.
    /// The default value is false, but subclasses used by unit tests might
    /// override this property's getter to return true.
    /// </summary>
    protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

    #endregion
}

A: Use the public version of the property to add the new item
Sources.Add(new SourceItem(selectedPath, new DirectoryInfo(selectedPath)));

You are currently adding the item to the private version of your property (_sources), while your UI is bound to the public version of the property (Sources), so your UI does not get the CollectionChanged notification the private version of the property raises, so does not know it needs to update.
The alternative is to simply raise the PropertyChanged event for your class manually to tell the UI to update. This is usually what I do when I want to add a lot of items to my collection at the same time, but only have the UI update once.
_sources.Add(new SourceItem(selectedPath, new DirectoryInfo(selectedPath)));
RaisePropertyChanged("Sources");


text:
Q: leaflet routing machine HTTP request failed I want to calculation the duration between to geolocalisation using leaflet routing machine but i got this error.
> message: "HTTP request failed: error" status: -1 target: ProgressEvent
> {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type:
> "error", …} url:
> "https://router.project-osrm.org/route/v1/car/2.279049917924877,48.83924675;2.2893811,48.8538898?overview=false&alternatives=true&steps=true&hints=;"
> __proto__: Object

Any solutions ?

A: you should overwrite the service url since https is not valid
use this property in options
serviceUrl: 'http://router.project-osrm.org/route/v1'


text:
Q: How do I install the empathy smilies (from maverick) in Pidgin? How do I install the empathy smilies (from maverick) in Pidgin? I really like the look of them.

A: If you mean the new Ubuntu speech-bubble emoticons, then try this:
http://feedproxy.google.com/~r/d0od/~3/VRw0IcDI77w/

A: I found grait collection of Pidgin artworks - smiles, status icons, etc. Its simple! Go to http://www.deviantart.com/ and search for "pidgin". There are meny ready-to-use packs!

A: I manually create a smiley plugin pack for pidgin using the empathy smilies. It didn't tak long and worked out great.


text:
Q: ObservableCollection and setting values Is this.
    private ObservableCollection<String> _Col;
    public ObservableCollection<String> Col
    {
        get
        {
            return _Col;
        }
        set
        {
            _Col = value;
        }
    }

the same as this
public ObservableCollection<String> Col { get; set }

using col.add("stringvaribleorsomething") they would both result in col being a collection of items?

A: Shortly - yes. But look at this article about auto-implemented properties in C#

A: If you want to both getter and setter methods like that, yes it is the same.But if you want to make your property read only,or set your property value depends on some condition you should use the first one.
Also the second one is called auto-implemented property.You can see the documentation


text:
Q: How to use @Autowired to dynamically inject implementation like a factory pattern I am fairly new to Sprint and am using Spring 3.x and roo1.1.1 for my application.
I have multiple implementation of an interface which would be @Autowired into other different classes. I would only be able to decide which implementation to go with at the runtime. This should be achieved with like a factory pattern.
public interface SomeInterface {
    public void doSomething();
}

Implementation 1.
public class SomeOb implements SomeInterface {
    public void doSomething() {
        //Do something for first implementation here
    }
}

Implementation 2.
public class SomeOtherOb implements SomeInterface {
    public void doSomething() {
        //Do something for first implementation here
    }
}

Now in my service i needed this Autowired like
@Service
public class MyService {

   @Autowired
   SomeInterface ob;
   //Rest of the code here

}

1) The logic to choose which implementation to be Autowired is only know runtime, so i cannot use the @Qualifier annotation to qualify this.
2) I tried to create a FactoryBean like
public class SomeFactoryBean implements FactoryBean<SomeInterface> {
@Override
public SomeInterface getObject() throws Exception {
    if(/*Somecondition*/) {
        return new SomeOb();
    } else
        return new SomeOtherOb();
}

@Override
public Class<? extends SomeInterface> getObjectType() {
    if(/*Somecondition*/) {
        return SomeOb.class;
    } else
        return SomeOtherOb.class;
}

@Override
public boolean isSingleton() {
    return false;
}
}

In the applicationContext.xml i have the  tag mentioned.
When i run the webserver i run into an error like
No unique bean of type [com.xxxx.xxxx.SomeInterface] is defined: expected single matching bean but found 3: [xxxx, xxxxxxx, xxxxFactory]

Can anyone please help me to resolve this issue. If i am not doing this right please direct me to do this the right way.
Thanks and appreciate any help,
jjk

A: Thanks for the suggestion. I was able to solve the problem with help from a colleague. What i was doing wrong

*

*I had the implementation of the SomeInterface with @Service. So this was picked up by the spring scanner and added to the bean.

*During trial and error i removed the @Component annotation from by FactoryBean implementation.

After making these changes it worked like a charm.

A: return true from isSingleton() if you only need one implementation of the bean for a given instance of your application
But I question your design.
I would always use properties files to switch out implementations like this. I once had to implement CAPTCHA integration for a site. We were prototyping with the JCaptcah and ReCAPTCHA APIs. I created a new interface that contained just the functionality we needed and then created implementations for both APIs. Using a placeholders in the Spring configuration file and Maven profiles, we could switch out the implementation class at compile time or deployment time, for example, mvn jetty:run -DcaptchaImpl=recaptcha or -DcaptchaImpl=jcaptcha.
Without knowing the task that you want to accomplish, it's hard to provide more advice.


text:
Q: Text-mining including patterns and numbers Dataset contains a free text field with information on building plans. I need to split the content of the field in 2 parts, the first part contains only the number of planned buildings, the other only the type of building. I have a reference lexicon list with the types of buildings.
Example
Plans<- c("build 10 houses ","5 luxury apartments with sea view",
          "renovate 20 cottages"," transform 2 bungalows and a school", "1 hotel")

Reference list
Types <-c("houses", "cottages", "bungalows", "luxury apartments")

Desired Output 2 colums, Number and Type, with this content:
Number  Type
10  houses
5   apartments
20  cottages
2   bungalows

Tried
matches <- unique (grep(paste(Types,collapse="|"), Plans, value=TRUE))

I can match the plans and types, but I can't extract the numbers and types into two columns.
I tried str_split_fixed and grepl using :digit: and :alpha: but it isn't working.

A: Assuming there is only going to be one numeric part in the string, we can extract the numeric part by replacing all the characters to empty strings. We create the Type column by extracting any of the string present in the Plans.
library(stringr)
data.frame(Number = as.numeric(gsub("[[:alpha:]]", "", Plans)),
           Type = str_extract(Plans, paste(Types,collapse="|")))

#  Number              Type
#1     10            houses
#2      5 luxury apartments
#3     20          cottages
#4      2         bungalows
#5      1              <NA>

For the 5th row, "hotel" is not present in Types so it gives output as NA, if you need to ignore such cases you can do it with is.na. Extracting number from the string part is taken from here.

A: You can also use strcapture from base R:
strcapture(pattern = paste0("(\\d+)\\s(",paste(Types,collapse="|"),")"),x = Plans,
           proto = data.frame(Number=numeric(),Type=character()))

  Number              Type
1     10            houses
2      5 luxury apartments
3     20          cottages
4      2         bungalows
5     NA              <NA>


text:
Q: optimizing calling an array of function pointers I have the following loop which calls all function pointers in an array:
for(auto f : program) {
   f();
}

I'd like to optimize this. So far, I've tried two methods:

*

*Tail recursion

*JITting threaded code

Here is the complete test code: https://coliru.stacked-crooked.com/a/d639f024b1222c54
The timing results on my machine (iMac Pro 8-Core) are:
naive: 0.530534
tail recursion: 0.265192
JIT threaded: 0.125106

Of course the functions all have to be modified to facilitate tail recursion, but that's ok. What would be less pleasant in terms of code cleanliness would be to put everything in one function and use something like computed goto (I've tried that too, actually, and computed goto is only slightly faster than tail recursion on my machine.)
Can I do better than tail recursion without JITting? (on iOS, JITting is not allowed)
Note that the functions cannot be re-ordered.

A: Yes. We can in fact beat the threaded code without JITting.
The test code consists of 100 possible functions. I wrote a little program to generate code for a 100x100 array of functions which call pairs of those 100 functions. The optimizer inlines the original 100 into the pairs. We now have:
naive: 0.534162
tail recursion: 0.269307
JIT threaded: 0.124608
pairs: 0.085922

This technique could be generalized to real-world cases by analyzing common sequences of function calls, rather than generating all possible pairs.
This could be combined with tail recursion for even faster dispatch.


text:
Q: Any clues on this Unity code not working? I have this function here to duplicate a UIPanel(Prefab) and its components. It duplicates, then succesfully assigns a objectname and enable/disable the Interactable setting of the button component. But the part where it sets the ''OnClick'' on my button does not work. I dont understand as I can play with other options of this button component...
Yes the function Click exists.
Yes I included my using using System.Collections.Generic; using UnityEngine.UI;
Any Help? Thanks.
public Text Title;
public Button Btn;

public void CreateEventSquares(string keyval, string valueval)
{
    string Event = (keyval);
    string Link = (valueval);
    Debug.Log("Event :" + Event + "Link is :" + Link);
    NewPanel = Instantiate(Event0);
    NewPanel.transform.SetParent(EventPanel.transform);
    NewPanel.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
    NewPanel.name = keyval;

    //Sets the button action to trigger Click function (Not Working)
    Btn = NewPanel.GetComponent<Button>();
    Btn.onClick.AddListener(Click);
    Btn.interactable = false;

    //Sets the title same as keyval (This Works)
    Title = NewPanel.GetComponentInChildren<Text>();
    Title.text = keyval;

}

Click
public void Click()
{
//do This
}

A: I've re-created this in Unity with your code and it's working perfectly fine for me! I think it's highly likely you are being thrown by the fact that the function is not showing up in the on click portion of the button in the Unity Inspector.
Try putting a debug.log in your click function and see what happens.
If you wanted to still define functions in the inspector you would have to use a Unity Event and then subscribe it to the onclick.
    [Serializable]
    public class ButtonClickedEvent : UnityEvent { }

    [SerializeField]
    public ButtonClickedEvent m_OnClick = new ButtonClickedEvent();

    Btn.onClick.AddListener(Click);

    void Click ()
    {
       m_OnClick.Invoke();
    }


text:
Q: Desktop menu, .desktop files and xdg-desktop-menu What's the relationship between .desktop files in the /usr/share/applications, the xdg-desktop-menu command and update-desktop-database command?
I'm trying to make a RPM that creates a desktop icon for my app. In the RPM, I install the vendor-appname.desktop file into /usr/share/applications. Then I have the following post-install script:
if [ -x "`which xdg-desktop-menu 2>/dev/null`" ]; then
    xdg-desktop-menu install $RPM_BUILD_ROOT/usr/share/applications/vendor-myapp.desktop
fi

if [ -x "`which update-desktop-database 2>/dev/null`" ]; then
    update-desktop-database &> /dev/null || :
fi

And the icon is not created. The icon IS created if I run the
xdg-desktop-menu install $RPM_BUILD_ROOT/usr/share/applications/vendor-myapp.desktop

command manually later on, as a non-root. If I do so as a root (which is, supposedly, how the RPM does it), the icon is not created. Also, I have a very strong suspicion that the update-desktop-database under if[] bit is not executed. It is executed  when I manually run the whole if[] statement.
Fedora Linux with Gnome.

A: On Fedora, be sure of:

BuildRequires: desktop-file-utils
Requires(post): desktop-file-utils
Requires(postun): desktop-file-utils

Then (%{SOURCE1} is your desktop file):

%install
[...]
desktop-file-install                                    \
--dir=${RPM_BUILD_ROOT}%{_datadir}/applications         \
%{SOURCE1}
[...]

%post
update-desktop-database &> /dev/null || :

%postun
update-desktop-database &> /dev/null || :

If you install your own icon, you also need to update the icon cache, adding in the relative specfile sections:

%post
touch --no-create %{_datadir}/icons/hicolor &>/dev/null || :

%postun
if [ $1 -eq 0 ] ; then
    touch --no-create %{_datadir}/icons/hicolor &>/dev/null
    gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || :
fi

%posttrans
gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || :

Refs:

*

*http://fedoraproject.org/wiki/PackagingGuidelines#Desktop_files

*http://freedesktop.org/wiki/Software/desktop-file-utils

*http://fedoraproject.org/wiki/Packaging/ScriptletSnippets#Icon_Cache


text:
Q: Bootstrap two navigation bars, secondary bar overlaps primary bar dropdown I have two bootstrap navigation bars on a rails app. The primary bar has a dropdown for user actions (sign-out, user profile, etc). However, the dropdown is being overlapped by the secondary bar.
Also, if I reduce the size of my viewport, the secondary bar collapses, but the primary bar's actions don't appear in the collapsed menu. How do I fix this?
My navbar code:

              <%= link_to(image_tag("cropped-sickbubble-logo-beta-3"),root_path) %>

                <% if user_signed_in? %>

                    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"><%= image_tag current_user.profile_image %> <%= "#{current_user.name}" %>
                    </button>

HTML

CSS

<%= link_to 'Log out', destroy_user_session_path, method: :delete %>

                <% else %>

<%= link_to 'Log In', new_user_session_path %>

<%= link_to 'Register', new_user_registration_path %>

                <% end %>

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

      </button>

<%= link_to "Categories", root_path %>

<%= link_to "Businesses", businesses_path %>

<%= link_to "Near me", geolocation_path, "data-no-turbolink": true %>

the custom css:
.firstnavbar {
  background-color: #282828;
  border-radius: 0px;
  border: 0px;
  min-height:53px;
  color: #ffffff;
  margin-bottom: 0px;
  ul.nav.navbar-nav, li  {
    font-weight: 400;
    a {
      color: #FFFFFF;
      background-color: #282828;
    }
    a:hover {
      background-color: #EEEEEE;
      color: #282828;
    }
  }
}

.secondnavbar
 {
    background-color: #FFFFFF;
     top: 50px;
     ul.nav.navbar-nav, li  {
       font-weight: 400;
       a {
         color: #282828;
         background-color: #FFFFFF;
       }
       a:hover {
         background-color: #EEEEEE;
       }
     }
 }

overlap image:
responsive menu bar not showing logout:

A: Set the z-index of the secondary nav to something less than the main nav's z-index (default is z-index: 1000):
.secondnavbar {
  z-index: 990;
}

A: try putting

 around the navbars, thats what I always do with the navbars.


text:
Q: Local storage stores string once and will not change I have this function where it shows the search listing in a card (recent searches). When I search something, it stores successfully in local storage but when I search another item the listing (recent search) doesn't update. Even after page refresh, the same first search stays in the card and won't update at all. Can anyone see whats happening and how to fix this? Thanks in advance!
Javascript:
function customDeal1() {

  var recentSearch = document.querySelector('#search').value;
  var HighScore = localStorage.getItem('highScore');

var matchArray = findDeals(HighScore, name).slice(0,1);
  const html = matchArray.map(place => {
    const regex = new RegExp(HighScore);
    const nameName = place.name.replace(regex, `<span class="hl">${HighScore}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `

${nameName}

${(place.price)} ${shop} ${shop1} ${shop2} ${shop3} ${shop4}

    `;
  }).join('') || '
 No Searches Found
';
  deal2.innerHTML = html;

if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

};
const deal2 = document.querySelector('.deal1');
setInterval(customDeal1,5000);

A: I think the problem is in this line
if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

it works at first because local storage is empty but once you execute the code
recentSearch will be stored in local storage which means the line above will be skipped
to fix this you will have to delete recentSearch from local storage before the line above or just save the data without the if statement because local storage overwrite data

A: how about this:
        function customDeal1() {

        var recentSearch = document.querySelector('#search').value;
        var HighScore = localStorage.getItem('highScore');
        deal2.innerHTML = recentSearch;

        // delete the conditions : if(!localStorage.getItem('highScore') ...
        localStorage.setItem('highScore', recentSearch);

    };
    const deal2 = document.querySelector('.deal1');
    setInterval(customDeal1, 5000);


text:
Q: i recently used JCrop in my laravel project , but although i choose a photo and its loaded , i get validation error image is requred I followed this https://www.youtube.com/watch?v=aflTCbGdzDc tutorial, and I managed to include Jcrop in my laravel project, everything is working fine. I click on choose image, I crop the image, and the image is shown in the jcrop image box. but when I submit the form. I get the error in my validation that says, image is required ( i wrote a validation for my image file). why am I getting this error ??? the image is showing in that box. what am I doing wrong ? or is there a problem with JCrop ?!! please help me.
This is the image when I upload :
https://drive.google.com/open?id=1qgEmA9RlKy_eilZohCLajGmnVfqWSB9E
This is the image when I submit and I get the error : https://drive.google.com/open?id=1gSCurwZ50TF_nMZZcWnJ4keBsJmcQKEh
Template Code:
<form method="post" action="{{route('userRegister')}}" enctype="multipart/form-data">
@csrf

all()) ? 'show' : 'hide'}}">

        @foreach($errors->all() as $error)

{{$error}}

        @endforeach

                        انتخاب عکس
                        <input type="file" name="filedata" id="filedata" >

                        در حال بارگذاری

بارگذاری

Validation Code:
public function rules()
{
    return [
        'filedata' => 'required|max:1024',
    ];
}

public function messages()
{
    return [
        'filedata.max' => 'سایز تصویر نمیتواند بیش از 2 مگابایت باشد',
        'filedata.required' => 'وارد کردن تصویر الزامی است',

    ];
}

I get this error in my console :
POST http://localhost:8000/server/ctrl.php?fileapi155834626282411 404 (Not Found)   FileAPI.min.js:2

A: After talking to you in the comments, it would appear your getting 404 errors on the FileAPI javascript files.
You were using the following configuration for your FileAPI:
var FileAPI = { debug:true, media:true, staticPath:'{{asset('crop-userpic\FileAPI')}}' };
This was setting your staticPath to the /resources/assets/crop-userpic/FileAPI directory, which placed them outside of the webroot of your website.
You need to set the staticPath to the location of the FileAPI javascript files within your public directory so they can be accessed by jcrop.
Example Usage

In the above example staticPath is the path to the files FileAPI.min.js and FileAPI.exif.js.
You should make sure you have those files accessible from within the /public/js/jquery.fileapi/FileAPI/.


text:
Q: Prove that we can't cover a 8x8 square with two 1x1 squares removed from two opposite corners with 1x2 rectangles Imagine an 8x8 square. Remove two 1x1 squares from two opposite corners. So now you have a shape containing 62 squares. Call it S.
We want to cover S with 1x2 rectangles. Prove that we can't do this.
Note : This question could be related to Hall's theorem on matchings. But i don't know how to convert the question to a graph.

A: This is a simple example of the colouring technique. Colour the squares alternately like a chessboard. Then the two removed squares have the same colour, so we are left with an unequal number of black and white squares. But a domino always covers one black square and one white square, so we cannot completely cover the remaining squares with dominos.


text:
Q: Remove running head in amsart Is it possible to remove the running head and page-numbering in an amsart document? I am submitting a document where there are not too many requirements, and I like how amsart looks like, but I need to get rid of the headers.

A: I've found that to get no headings and no page numbers I need
\pagestyle{empty}

in the preamble, and
\thispagestyle{empty}

in the document test after \maketitle

A: Put
\pagestyle{plain}

in the preamble.


text: Q: Can't Compile Java GCJ-6.2.0 Mac OS X Sierra I have written a basic program in the Java programming language, and it compiles normally with Oracle Java, but when using GCJ to compile with this command "gcj-6.2.0 main.java"I get this error "gcj-6.2.0: error trying to exec 'ecj1': execvp: No such file or directory". Every other GCC compiler works fine besides Java, I am on a Mac and installed the latest version of GCC yesterday. What can I do?


text:
Q: Purple Screen of Death after changing Nvidia X Server prime profile to Performance mode For an Edge AI system I'm using an AMD Ryzen 5 5600G based compute platform with a NVIDIA Tesla T4 for the AI workloads.
After setting the NVIDIA X Server Prime profile from "NVIDIA on demand" to "NVIDIA Performance Mode" (not knowing was it does tbh, I was blinded by a the word performance) and rebooting, I was greeted with a purple screen of death on my Ubuntu 20.04.
Removing the GPU solved the issue but here I was not able to undo the change in settings or resolve the issue otherwise. When plugging the GPU back in, the purple screen returns on startup.
Does someone has any tips on how to solve this? E.g. resetting all NVIDIA X Server settings somehow? I was not able to find any guide on how to do that.
Thx a lot!
BR
Kevin

A: Remove all NVIDIA packages.

*

*Remove all the nvidia packages.
sudo apt update
sudo apt upgrade
sudo apt autoremove
sudo apt-get remove --purge nvidia*
sudo apt-get remove --purge "nvidia*"

*If you have added an Nvidia PPA to /etc/apt/sources.list remove that PPA by prefacing its line in sources.list with a # to comment it out. Run sudo apt update to refresh the list of available software.

*Reboot with sudo reboot
Optionally you can reinstall the recommended NVIDIA proprietary graphics drivers after they have been removed. The autoinstall command of ubuntu-drivers installs drivers that are appropriate for automatic installation including their dependencies.
sudo ubuntu-drivers autoinstall && sudo reboot


text:
Q: How to add an integer value into NSMutableArray? NSMutableArray * val;
val = [[NSMutableArray alloc] initWithCapacity:15];

/*int outlineWidth = barOutlineWidth;
int outlineHalfWidth = (outlineWidth > 1) ? outlineWidth * 0.5f : 0;
 */
for ( Bar * obj in values )
{
  // calcualte the bar size
  float value  = [obj value];
  float scale  = ( value / maxValue );

  // shift the bar to the top or bottom of the render line
  int pointY   = lineHeight + ( (lineWidth * 0.5f) * ( ( value >= 0.0f ) ? -1 : 1 ) );
  int barHeight = height * scale;
  NSLog(@"%d", barHeight);
  CGRect barRect = CGRectMake(pointX, pointY, width, -barHeight);
  [val addObject:[NSNumber numberWithInt:barHeight]];
                     NSLog(@"%d", val);

I want to add the barheight (int) into array val.
Is this possible?
while running the code,
session started at 2010-09-16 13:21:50 +0530.]
2010-09-16 13:21:53.791 BarGraphSample[3168:20b] 78
2010-09-16 13:21:53.797 BarGraphSample[3168:20b] 69398112
2010-09-16 13:21:53.807 BarGraphSample[3168:20b] 235
2010-09-16 13:21:53.812 BarGraphSample[3168:20b] 69398112
2010-09-16 13:21:53.813 BarGraphSample[3168:20b] 156
2010-09-16 13:21:53.814 BarGraphSample[3168:20b] 69398112

this is the output.
Here the actual barheights are 78,235,156,
while printing the array val.
Im getting like values like "69398112"
What should I do?

A: You can only add pointers to objects to an NSMutableArray. If you use the NSNumber class though to wrap your integer, you should then be able to add that to the array.
int x = 10;
NSNumber* xWrapped = [NSNumber numberWithInt:x];
NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:15];
[array addObject:xWrapped];
int xOut = [[array lastObject] intValue]; //xOut == x;

Hope this helps.

A: Add a number instead.
NSNumber* foo = [NSNumber numberWithInteger:42];

or using boxed literals:
NSNumber* foo = @(42);

then add foo.

A: The issue is with your NSLog string namely
NSLog(@"%d", val);

%d is in fact the format specifier for an integer (int). You are passing it a NSMutableArray object.
Change the NSLog to
NSLog(@"%@", val);

The %@ expects an object, and this will typically print out [myObject description], in this case a description of your val array.

A: Convert Int to NSNumber then add to your array

A: This is a simple way:  @(yourInt)
int value = 5;
NSMutableArray * anArray  = [[NSMutableArray alloc] init];
[anArray addObject: @(value)];

more information about at-compiler-directives


text:
Q: Titanium Alloy Push Notification Subscribed But Listener Not firing Up I need to make a push notification listener, My code for this is below and it runs perfect till the subscription and the dashboard confirms it is subscribed successfully, but the problem occurs with the receiver.
Alloy.Globals.ServiceAddress = "my service address";
Ti.API.info("1");
var CloudPush = require('ti.cloudpush');
var Cloud = require("ti.cloud");
var deviceToken = null;

loginUser(); // flow starts from here
function loginUser() {
  Cloud.Users.login({
    login: 'User',
    password: 'Password'
  }, function(e) {
    if (e.success) {
      var user = e.users[0];
      //    alert("Loggin successfully");
      getDeviceToken();
    } else {
      alert("Error2*** :" + e.message);
      //Ti.API.info('error ')
    }
  });
}

function getDeviceToken() {

  if (Ti.Platform.Android) {
    CloudPush.debug = true;
    CloudPush.focusAppOnPush = false;
    CloudPush.enabled = true;
    CloudPush.showAppOnTrayClick = true;
    CloudPush.showTrayNotification = true;
    CloudPush.singleCallback = true;
    CloudPush.singleCallback = true;
    CloudPush.retrieveDeviceToken({
      success: deviceTokenSuccess,
      error: deviceTokenError
    });
  }
}

// Enable push notifications for this device
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
  deviceToken = e.deviceToken;
  alert(e.deviceToken);
  subscribeToChannel(deviceToken);
}

function deviceTokenError(e) {
  alert('Failed to register for push notifications! ' + e.error);
}

// Process incoming push notifications
function subscribeToChannel(deviceToken) {

  // Subscribes the device to the 'news_alerts' channel
  // Specify the push type as either 'android' for Android or 'ios' for iOS
  Cloud.PushNotifications.subscribeToken({
    device_token: deviceToken,
    channel: 'Vision', //'You_App',
    type: Ti.Platform.name == 'android' ? 'android' : 'ios'
  }, function(e) {
    if (e.success) {
      alert('Subscribed');
      SendNotification(deviceToken);
    } else {
      // indicator.visible = false;
      alert('Subscribe Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
    }
  });
}

function SendNotification(to_deviceToken) {
  alert('sendnot');
  Cloud.PushNotifications.notifyTokens({
    channel: 'My Cannel',
    to_tokens: to_deviceToken,
    payload: 'Welcome to push notifications'
  }, function(e) {
    if (e.success) {
      alert('Success Send');
    } else {
      alert('Send Error:\n' +
        ((e.error && e.message) || JSON.stringify(e)));
    }
  });
}

When I add event-listener to push notifications it doesn't even fire up however, the client is saying it is connected.
<!-- language: lang-js -->
CloudPush.addEventListener('callback', function (evt) {
    alert('rec');
    alert("Notification received: " + evt.payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function (evt) {
    Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function (evt) {
    Ti.API.info('Tray Click Focused App (app was already running)');
});

PS. I have searched and already read related threads Like this one
I am attaching the log to make it clarify that subscription and notification send is working properly
Push notification Log
and
Connected Clients

A: Solved
I was compiling with titanium api level 4.1.1.v20151203143424 with CloudPush module version 3.2.1
I migrated to titanium 6.0.0.v20160202173231 with cloudpush module version 3.4.1
and all set see in this pic


text:
Q: How to print variable from another file In the code bellow I am receiving the position of XAUUSD from Interactive
Brokers. Can someone tell me how can I catch updated value of the variable maypos in another python file?
from ib.opt import Connection, message
from ib.ext.Contract import Contract
from ib.ext.Order import Order
import time
import os
import datetime
import random

def error_handler(msg):
    print ("Server Error: %s" % msg)
    return

def replies_handler(msg):
    print ("Server Response: %s, %s" % (msg.typeName, msg))
    return

def print_portfolio_position(msg):

    if msg.contract.m_symbol == "XAUUSD":
       mypos = msg.position
       print("Position:", msg.contract.m_symbol, msg.position,
               msg.marketPrice, msg.contract.m_currency, msg.contract.m_secType)

if __name__ == "__main__":

    while 1:

        time.sleep(5)
        conn = Connection.create(port=4096, clientId=1)
        conn.connect()
        conn.register(error_handler, 'Error')
        conn.register(print_portfolio_position, 'UpdatePortfolio')
        conn.register(replies_handler, 'UpdateAccountValue')
        conn.reqAccountUpdates(1, '')
        time.sleep(2)
        conn.disconnect()

A:
Question: how can I catch updated value of the variable maypos in another python file?

from another python file import maypos

value = maypos.updated value


text:
Q: How to Organize, build and ship NodeJS applications specific to different customers We are building an Aurelia application.  We have common login page and home page for our customers.  But each customer will have their special customer page, which is very specif to them.  These cusomer specific pages should only be visible to the customer and not visible to others.  I need to find a proper way to to create a sub folder in my project for each customer to have their specific resources.  Even when we bundle the applicaiton for a specific customer, we should export only their own resources.

A: It sounds like you are using dynamic routing. There have been a few folks asking this question publicly. One example is here https://discourse.aurelia.io/t/dynamicaly-load-routes/1906
Note that Aurelia also works with remote view, as an example is here https://codesandbox.io/s/8ljmrq3vql
One common things about ultra dynamic scenarios is you need a proper dynamic script loader (requirejs, systemjs, fuseboxjs), not bundler (webpack).


text:
Q: Whenever I try to add a button to my actionbar, the items are added under the overflow menu I am trying to add a simple button to my action bar, but when I try to use the following code, the items are added as items under the overflow menu, not on the actionbar itself.  Any help would be appreciated,
Jacob
Here is my Java:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_review, menu);

    return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case android.R.id.home:

            super.onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);

    }
}

and my XML:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/seda"
        android:icon="@drawable/redpinreal"
        android:title="Hello Worldh"
        android:showAsAction="withText|always"/>

</menu>

I also have this enabled:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

A: Part of your code (android:showAsAction, instead of yourapp:showAsAction) is attempting to use the native action bar. Part of your code (getSupportActionBar(), instead of getActionBar()) is attempting to use the appcompat-v7 action bar backport. Choose one and stick with it.


text:
Q: How to get Grandson ActiveRecord Object class Chapter < ApplicationRecord
  has_many :courses
end

class Course < ApplicationRecord
  belongs_to: chapter
  has_many :modules
end

class Moudule < ApplicationRecord
  belongs_to: course
end

I want to get Chapter's modules
I write a code.
module_list = []
chapter = Chapter.find(1)
chapter.courses.each |course| do
  course.modules.each |module| do
    module_list.push(module)
  end
end

module_list

but it is not smart.

*

*many each nest.

*module_list is not ActiveRecordObject.

Is there good way?

A: This is what "through" associations are for:
class Chapter < ApplicationRecord
  has_many :courses
  has_many :modules, :through => :courses
end

chapter = Chapter.find(1)
chapter.modules


text:
Q: Analyze 'return' statement inside function Sometimes inside one function we need to use the return statement several times.
When developer changes a function with multiple returns inside, it's easy to oversee some parts of code where yet another return was "hidden".
If unit tests do not cover all possible paths, disaster is guaranteed - it's only a question of time.
def my_function():
    '''Multiple "return" inside'''

    if condition 1:
        return 1, 2, 3
    if condition 2:
        return 2, 3, 4

    return 5  # this is wrong: only 1 value returned, while 3-tuple expected

Let's assume here: last return is wrong, because other callers expect tuple of 3 items.
I wonder if you know an easy way how to catch such parts of code automatically? I thought I could use AST, but I could not find any useful example of this.
This question is about automatic code analysis and listing such cases found - could be with running a separate script.
Of course I could write a try-to-guess parser (with e.g. regex) and then 'manually' check all unclear cases, but maybe there is a simpler way...

A: Depending on what version of Python you're using and what you really want to achieve, there are several ways to refactor the code.
One way, as has been already suggested, is to use Type Hints in Python 3.
Another way is refactor your code such that instead of using multiple return statements, you call other more atomic methods that handle those conditions and return the appropriate values. You use exception handling in those atomic methods to make sure the output is as desired, or raise an exception if final return type is unexpected.
def my_function():
    '''Multiple "return" inside'''

    if condition 1:
        output = func_handle_condition_one()
    if condition 2:
        output = func_handle_condition_two()

    output = some_other_value

    if type(output) is not tuple:
        raise TypeError("Invalid type for output")
    return output

Additionally, ensure that you're using the right constructs for your conditions (such as whether you want to use multiple if or the if-elif-else construct). You could even re-factor your calling code to call the right function instead of calling one that has so many conditional statements.

A: Why not set a variable that gets returned at the end and check for its length
def my_function():
    '''Multiple "return" inside'''

    return_value=(0,0,0)

    if condition 1:
        return_value=(1, 2, 3)
    elif condition 2:
        return_value=(2, 3, 4)
    else:
        return_value=5  # this is wrong: only 1 value returned, while 3-tuple expected

    try:
        if len(return_value)==3:
            return return_value
        else:
            print("Error: must return tuple of length 3")
    except:
        print("Error: must return tuple")

A: My proposal for the final type check of the result would be:
assert isinstance(return_value, tuple) and len(return_value) == 3

Advantage: as assert is easily switched off after debugging phase; still succinct statement for formulating the expectation.


text:
Q: How do find Name and Assembly js asp.net file i want active gzip for js in asp.net. i use ScriptManager and this code:
    <asp:ScriptManager ID="ScriptManager1" runat="server">
<CompositeScript>
<Scripts>
<asp:ScriptReference  Path="~/Scripts/jquery.min.js" />
<asp:ScriptReference Name="MicrosoftAjax.debug.js" Assembly="AjaxControlToolkit, Version=4.1.7.123, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e" />
<asp:ScriptReference Name="MicrosoftAjaxWebForms.debug.js" Assembly="AjaxControlToolkit, Version=4.1.7.123, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e" />
</Scripts>
</CompositeScript>
</asp:ScriptManager>

its working. but i have one js and do not know Name and Assembly. plase help me for find name and assembly this js file.
File:
WebResource.axd?d=qRVKOjs7_pTkijfl7uZM8g2&t=634879765642719078
Summary Code js:
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
    if (typeof(Page_ClientValidate) == 'function') {
        validationResult = Page_ClientValidate(options.validationGroup);
    }
}
if (validationResult) {
    if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
        theForm.action = options.actionUrl;
    }
    if (options.trackFocus) {
        var lastFocus = theForm.elements["__LASTFOCUS"];
        if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
            if (typeof(document.activeElement) == "undefined") {
                lastFocus.value = options.eventTarget;
            }
            else {
                var active = document.activeElement;
                if ((typeof(active) != "undefined") && (active != null)) {
                    if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
                        lastFocus.value = active.id;
                    }
                    else if (typeof(active.name) != "undefined") {
                        lastFocus.value = active.name;
                    }
                }
            }
.
.
.

A: Apparently, there's nothing in the latest version of the framework that would compress the resources served by WebResource.axd. You will have to do it yourself.
The good news is that someone else already did the work. See here:
http://madskristensen.net/post/Optimize-WebResourceaxd-and-ScriptResourceaxd.aspx


text:
Q: Trigonometric development help. I need help with the following trigonometric development:
$ x = r(\theta)\cos\theta$
$ y = r(\theta)\sin\theta$
this gives:
$ x' = r'(\theta)\cos\theta - r(\theta)\sin\theta$
$ y' = r'(\theta)\sin\theta + r(\theta)\cos\theta$
My problem is that I cannot understand this development:
$(x')^2 + (y')^2 = r(\theta)^2 + r'(\theta)^2$
Can someone please explain to me how the last development is made and how you do / see that it is valid.
I am also a bit puzzled about why $x'$ and $y'$ is not written $x'(\theta)$ & $y'(\theta)$.
Thank you!

A: you need to use the fact that $\sin^2(\theta) + \cos^2(\theta) = 1$:
$$
x' = r(\theta) \cos \theta - r(\theta) \sin \theta \Rightarrow x'^2 = r'(\theta)^2 \cos^2 \theta - 2 r(\theta) r'(\theta) \sin \theta \cos \theta + r(\theta)^2 \sin^2 \theta
$$
$$
y' = r(\theta) \sin \theta + r(\theta) \cos \theta \Rightarrow y'^2 = r'(\theta)^2 \sin^2 \theta + 2 r(\theta) r'(\theta) \sin \theta \cos \theta + r(\theta)^2 \cos^2 \theta
$$
$$
\Rightarrow x'^2 + y'^2 = r(\theta)^2 (\sin^2 \theta + \cos^2 \theta) - 2 r(\theta) r'(\theta) \sin \theta \cos \theta + 2 r(\theta) r'(\theta) \sin \theta \cos \theta + r'(\theta)^2 (\sin^2 \theta + \cos^2 \theta) = \left(r(\theta)^2 + r'(\theta)^2\right) (\sin^2 \theta + \cos^2 \theta) = / using~\sin^2 \theta+\cos^2 \theta = 1 / = r(\theta)^2 + r'(\theta)^2
$$

A: Just expand
$$\begin{eqnarray*}
\left( x^{\prime }\right) ^{2} &=&\left( r^{\prime }\left( \theta \right)
\cos \theta -r\left( \theta \right) \sin \theta \right) ^{2} \\
&=&\left( r^{\prime }\left( \theta \right) \right) ^{2}\cos ^{2}\theta
-2r\left( \theta \right) r^{\prime }\left( \theta \right) \sin \theta \cos
\theta +\left( r\left( \theta \right) \right) ^{2}\sin ^{2}\theta  \\
\left( y^{\prime }\right) ^{2} &=&\left( r^{\prime }\left( \theta \right)
\sin \theta +r\left( \theta \right) \cos \theta \right) ^{2} \\
&=&\left( r^{\prime }\left( \theta \right) \right) ^{2}\sin ^{2}\theta
+2r\left( \theta \right) r^{\prime }\left( \theta \right) \sin \theta \cos
\theta +\left( r\left( \theta \right) \right) ^{2}\cos ^{2}\theta,
\end{eqnarray*}$$
sum $(x^{\prime})^2+(y^{\prime })^2$  and use the identity $\sin ^{2}\theta +\cos ^{2}\theta =1$.


text:
Q: Remove first day of data from multiple tracked individuals I have a database of many individuals that have been tracked for a long time and I'm trying to remove the first 24h of data for each one of them. This is done to remove data on potentially unnatural behaviour as a result of manipulation during the tagging process in future analyses. It has been tricky to solve because many have different starting dates.
Thanks.
My data is basically looks like this:
datetime             Ind           Lat   Long

2019-04-02 08:54:03  Animal_1      Y      X
2019-04-02 09:01:13  Animal_2      Y      X
2019-04-02 15:45:22  Animal_1      Y      X
2019-04-03 17:31:50  Animal_1      Y      X
2019-04-03 21:24:38  Animal_1      Y      X
2019-04-04 00:01:24  Animal_1      Y      X
2019-04-04 00:01:24  Animal_1      Y      X
2019-04-05 03:32:56  Animal_1      Y      X
2019-04-05 18:42:07  Animal_3      Y      X
2019-04-06 17:16:24  Animal_1      Y      X

.
.
.
2021-10-14 12:34:56  Animal_1      Y      X
2021-10-15 16:05:50  Animal_20     Y      X
2021-10-15 22:29:37  Animal_15     Y      X

I have tried adapting code I've found in other relatively similar questions but haven't succeeded..

A: How about something like this:
library(dplyr)
library(lubridate)
dat %>%
  arrange(Ind, datetime) %>%
  group_by(Ind) %>%
  filter(datetime > min(datetime) + hours(24))


text:
Q: Is it possible to pass a function or sub as an argument in Excel VBA? I want to pass a function/sub name as an argument so that I can call it within another function/sub in Excel VBA. Is this possible? If so, what is the type I set it as? I tried setting as Variant but that didn't work. I'm not sure what else to try.
Here is a basic outline of the code I'm working on. Including my failed attempt at using Variant.
As you can see I'm trying to have waitingBBG check a different range each time and then call a different sub each time. That's why I want to be able to specify which sub to call after waitingBBG is done.
Update: I updated the code with Application.Run instead of Call
Sub part_1
    Dim calculation_rng as String
    calculation_rng = "A1"

    Call waitingBBG(calculation_rng, "part_2")
End Sub

Sub waitingBBG(calculation_rng As String, call_id As Variant)

    If Application.WorksheetFunction.CountIfs(Range(calculation_rng), "#N/A Requesting Data...") > 0 Then
        'Check every 1 second
        Application.OnTime Now + TimeValue("00:00:01"), "waitingBBG"
    Else
        'Call rest of code
        Application.Run "'my_addin.xlam'!" & call_id
    End If

End Sub

Sub part_2
    Dim calculation_rng as String
    calculation_rng = "B1"

    Call waitingBBG(calculation_rng, "part_3")

End Sub

Sub part_3
    Msgbox("Success")
End Sub

A: @MathieuGuindon provided the correct solution. Thank you!
Basically, I needed to pass the function name as a string and use Application.Run instead of Call
Also,
Application.OnTime Now + TimeValue("00:00:01"), "waitingBBG"

needed to be changed to
Application.OnTime Now + TimeValue("00:00:01"), "'waitingBBG """ & calculation_rng & """,""" & call_id & "'"

to reflect the changes.

A: Sub sub1()
Dim a As String
a = "hii"
sub2 (a)
End Sub
Sub sub2(val As String)
If val = "hi" Then

MsgBox (val)
Else
MsgBox ("sub2 else")
sub3 (val)
End If
End Sub

Sub sub3(val1 As String)
MsgBox (val1)
End Sub


text:
Q: Fluent bit larger log from docker I want to read logs from stdout where the Java app logs. Logs are getting by forward as parser I used docker. Problem is that some of the logs is huge, especially where is some stack trace. The log is split into many logs and problem is that the log is visible even exception message. Configuration is going to run on Kubernetes but for the test I use docker.
[INPUT]
   Name              forward
   Listen            0.0.0.0
   Port              24224

[FILTER]
    name             parser
    match            *
    key_name         log
    parser           docker

[OUTPUT]
    Name   stdout
    Match  *

I tried to contact logs but it doesn't work using this configuration: https://docs.fluentbit.io/manual/pipeline/filters/multiline-stacktrace#docker-partial-message-use-case

A: This setup works for me:
fluent-bit.conf
[SERVICE]
  flush                 1
  log_level             info
  parsers_file          parsers_multiline.conf

[INPUT]
  name                  tail
  refresh_interval      5
  path                  /var/log/*.log
  read_from_head        true

[FILTER]
  name                  multiline
  match                 *
  multiline.key_content log
  multiline.parser      go, multiline-regex-test

[OUTPUT]
  Name http
  Match *
  Host data-prepper
  Port 2021
  URI /log/ingest

parsers_multiline.conf
[MULTILINE_PARSER]
    name          multiline-regex-test
    type          regex
    flush_timeout 1000
    rule      "start_state"   "/^2022.*/"  "cont"
    rule      "cont"          "/^(\D{4})/"                     "cont"

sources:

*

*https://docs.fluentbit.io/manual/administration/configuring-fluent-bit/multiline-parsing

*https://docs.fluentbit.io/manual/pipeline/filters/multiline-stacktrace


text:
Q: ruby object model and class declaration i was trying some code about how classes are declared internally and what happens when a class is declared. I got that when a class is declared, an object of 'Class' is created and a constant with the name of the declared class is created. eg
MyClass = Class.new
MyClass.class => Class
MyClass.superclass => Object
Class.constants.include? :MyClass => true

i also tried
x = Class.new => #<Class:0xd886938>
x.class => Class
x.superclass => Object
Class.constants.include? :x => false #why so???

it means that 'x' is a class. i m confused cause
class x
  def say_hi
    'hi'
  end
end

gives
SyntaxError: (irb):121: class/module name must be CONSTANT

why is this happening?
---UPDATE---
i tried
def x.x_method
  'x class method'
end

and did
x.methods.include? :x_method => true

similarly
x.singleton_methods.include? :x_method => true

and mainly
x.methods - MyClass.methods => [:x_method]

The above line points that x is a class since it's an object of class Class. Since all user defined classes are objects of class Class, then their initial methods should also be the same unless some singleton method is declared for a specific class(x in the above case has a singleton method)
x => #<Class:0xd886938>
obj_x = x.new  => #<#<Class:0xd886938>:0xd30caac>
obj_x.class => #<Class:0xd886938>

The above code further strengthens the assumption that x is a class since it's allowing me to create new objects. if x would have been an instance then new would have failed with an error.
My question is that, why is ruby allowing me to declare a class in a particular fashion? and if it isn't a class then why is it behaving like one?

A: The Ruby interpreter only sees things that start with an uppercase letter as constants. That's why your "class" x isn't included in Class.constants
From This:

Naming conventions
Ruby enforces some naming conventions. If an identifier starts with a
  capital letter, it is a constant. If it starts with a dollar sign ($),
  it is a global variable. If it starts with @, it is an instance
  variable. If it starts with @@, it is a class variable.

Since class names are supposed to be constants, x in your code isn't the name of the class. It is a variable that holds a class, that happens to have no proper assigned name. (Which you can verify by entering x.name and seeing it returns nil, as suggested by @ZachKemp on his answer)
In short, you can't give a class a name that starts with a lowercase character in Ruby.

A: As you've discovered, you can treat classes as first class objects in Ruby. In the case where you create a new class as x = Class.new, you've assigned a class instance object to a variable, which is not the same as giving it a name (you can send the query method x.name to verify the name is nil). You can then assign that variable to a constant (MyClass = x) to give it a permanent name.
The class declaration is a keyword that expects a constant to begin with. Both methods of creating classes create the same thing (an instance of Class), and you can use either method you wish (though the first is generally only used in special circumstances).


text:
Q: Ubuntu Desktop on Rpi 4 8GB no display after boot So I used the regular raspberry-pi-imager tool for windows and flashed the "Ubuntu Desktop 21.10 (RPi 4/400)" on my brand new raspberry pi 4 8GB ram model.
During the boot, the regular RGB spectrum is shown and then I'm presented with the loading screen with the ubuntu logo in the middle of the screen and the spinner below that and the "ubuntu" text below the spinner.
After a while the screen goes blank and nothing ever pops up, my monitor goes to standby mode.
I've tried the hdmi_safe=1 on the config file and no change.
I've tried disconnecting and reconnecting the hdmi plug still no output on my monitor.
To make sure my RPi4 is not damaged, I installed the Raspberry Pi OS and that worked as expected.
Then, I flashed it with the EEPROM bootloader and it successfully worked.
I was using a 32GB microSD card so I did it again with a 16GB one yet the same issue.
Any help would be great.


text:
Q: App crashes with Media Player my quiz app crashes when is to expect to hear a sound for right/wrong answer. This used to work, now it doesn't and I dont understand why. Can someone helpe me out? The code:
import java.util.List;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.vtorferreira.R;

public class QuizActivity extends Activity {

List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

   final MediaPlayer wrong_answer= MediaPlayer.create(this,   R.raw.wrong_answer);
   final MediaPlayer correct_answer= MediaPlayer.create(this, R.raw.correct_answer);

    DbHelper db=new DbHelper(this);

    quesList=db.getAllQuestions();
    currentQ=quesList.get(qid);
    txtQuestion=(TextView)findViewById(R.id.textView1);

    rda=(RadioButton)findViewById(R.id.radio0);
    rdb=(RadioButton)findViewById(R.id.radio1);
    rdc=(RadioButton)findViewById(R.id.radio2);

    butNext=(Button)findViewById(R.id.button1);
    setQuestionView();
    butNext.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View v) {
            RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());

            if(currentQ.getANSWER().equals(answer.getText()))
            {
                correct_answer.start();
                score++;
                Toast.makeText(getApplicationContext(),"Correct!", Toast.LENGTH_SHORT).show();

            }else{
                wrong_answer.start();
                Toast.makeText(getApplicationContext(),"Wrong...", Toast.LENGTH_SHORT).show();
            }
            if(qid<9){
                currentQ=quesList.get(qid);
                setQuestionView();
            }else{
                Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
                Bundle b = new Bundle();
                b.putInt("score", score); //Your score
                intent.putExtras(b); //Put your score to your next Intent
                startActivity(intent);
                finish();
            }
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_quiz, menu);
    return true;
}
private void setQuestionView()
{
    txtQuestion.setText(currentQ.getQUESTION());
    rda.setText(currentQ.getOPTA());
    rdb.setText(currentQ.getOPTB());
    rdc.setText(currentQ.getOPTC());
    qid++;
}
public void onBackPressed(){

 }
}

The log:
     java.lang.NullPointerException: Attempt to invoke virtual method 'void  android.media.MediaPlayer.start()' on a null object reference
Thanks in advance

A: You should write correct_answer.prepare(); before correct_answer.start();


text:
Q: How to add a color picker in a rails form I'm building a rails app and want the user to be able to choose a color at some point. To do this, I tried to implement a color picker in my form with the 'jquery-minicolors-rails' gem.
This question: How to add Colorpicker in Rails Active Admin? is pretty similar to what I want to do I guess but I couldn't make it work.
Here is what I tried:
I added gem 'jquery-minicolors-rails' in the Gemfile and ran bundle install.
app/frontend/packs/application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

require("jquery")
require("jquery.minicolors")

require("./application.scss")
require("./application_front.js")
require("./application_back.js")

jQuery( function($) {
    $(".colorpicker").minicolors()
});

In this file, I added the lines containing jquery and jquery.minicolors as well as the $(".colorpicker").minicolors() snippet.
app/frontend/packs/application.scss
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

/*
 *= require jquery.minicolors
 */

.turbolinks-progress-bar {
  background-color: #3355c5;
}

Finally, my form:
<%= form_with(model: @my_model, local: true, html: {class: "form-group"}) do |f| %>
  <%= f.input :name, input_html: { class: 'colorpicker' } %>
  <%= f.submit("Confirm", id: "confirm_button") %>
<% end %>

Leaving f.input provokes an error when I reach that page undefined method 'input' for ... so I tried replacing with f.text_field for example but I just get a simple text field, I can't manage to make the color picker appear on this page.
I'm using Rails 6.0.2.1 and Ruby 2.6.3
Thanks for your help.
If you have any other means to add a color picker, feel free to tell me, I'm not attached to jquery-minicolors gem.

A: If you are not attached to that package then you can try the one provided by html instead. See this example from w3schools for the usage:
https://www.w3schools.com/tags/att_input_type_color.asp


text:
Q: python mysql dictionary I have been using the dictcursor in MySQL with Python, the problem is how I can retrieve an specific record without having to iterate in all the dictionary, actually I am using this:
data=cursor.fechall
for item in data:
    if item["article"]==articledesc:
           do something
           break

is there a way to access the element of the dictionary created directly, without having to iterate over all the elements with a for loop
thanks

A: If you only require a single article, then change your query to add a where clause:
SELECT ...
FROM ...
WHERE article = %s

Filtering a result set having retrieved more than you need is not a good idea from an efficiency point of view.
If you're retrieving a larger resultset and picking multiple articles out by name later on, you could build a rudimentary index in your first pass; then use this to efficiently access the rows by name:
data = cursor.fetchall()

article_index = dict((item["article"], item) for item in data)

article = article_index.get(articledesc)
if article:
   #do something

A: Not directly, you can build another dictionary, but it is an implicit loop:
data_article = dict((item['article'], item) for item in data)

and then you can access data directly:
myitem = dict_article[articledesc]


text:
Q: how to get elements in "div id=0" using PHP Simple HTML DOM Parser I have downloaded and included PHP Simple HTML DOM Parser but when I try to get data from
 it just gets data from every div id.
$html_data=$htmlfile->find('div[id=0]',0);
but if I used div[id=1] , it works perfectly .
any ideas ?

data0

data1

data2

data3

html file is like above , I need to get data0 using find('div[id=0]',0) it is not working but if I type find('div[id=1]',0) I can get data1 without a problem.
NOTE
I have other div id=idname files in the html as well .

A: Assuimg extra ('div[id=0]',0) , 0 here in .. you may be selecting the first element.
$html_data=$htmlfile->find('div[id=0]',0);

So , instead use ..
$html_data=$htmlfile->find('div[id=0]')[0];

to get the first element.


text:
Q: Open pdf in new tab upon form submission I currently have a form that redirects to an email handler php file. Currently we email the user a pdf when they submit the form, but I'd like to change it to where the pdf just opens in a new tab when submitted. Don't mind the terrible naming conventions. The below code is giving me a WordPress error, and I'm not sure how to get it working properly.
<?php

header('Content-type: application/pdf');

header('Content-Disposition: inline; filename="$_POST["cm-f-djuiyhkr"]');

readfile($_POST['cm-f-djuiyhkr']);

?>


text:
Q: c# split string I have this code that splits a specific string.
str = "\n\nThis\nString\nis\nsplit\ninto\narray";
string[] delimiterChar = { "\n" };

var splitArray = str.Split(delimiterChar);

The split array is simple array of strings, but why isn't it possible to remove the first 2 item by using:
splitArray[0].remove();
splitArray[0].remove();

A: If you need to remove empty entries, then just specify it in the split method. There is no need to remove them manually.
var splitArray = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries);

If you want to specifically remove certain specific elements, then you can convert the array (non-mutable) to a list (mutable), and work on it like:
var splitList = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries).ToList();
splitList.RemoveAt(0);

A: This might be one of the solution which might get the desired result.
string str = "\n\nThis\nString\nis\nsplit\ninto\narray";
str = str.TrimStart('\n');
var splitArray = str.Split('\n');

A:
yes,but sometimes the string contains random string at the first 3 indexes..
  so i want to split this simple string into Array via Split and remove .
The split array is simple array of strings, but why isn't it possible to remove the first 2 items

Split it and then skip whatever number of items you wish using Linq:
// I am skipping 3 for example
var splitArray = str.Split(delimiterChar).Skip(3).ToList();

Make sure to add this to the list of using statements:
using System.Linq;


text:
Q: How do I access the associated Renderer object from within a QQuickFramebufferObject I tried to store it as a member pointer on creation, so it can be accessed later:
QQuickFramebufferObject::Renderer* MyItem::createRenderer() const {
    m_renderer = new MyItemRenderer(this);
    return m_renderer;
}

... but this doesn't work - Qt requires createRenderer to be a const method, so I can't assign to m_renderer within it. I could use mutable but that's a hack and is risky because it may break assumptions in Qt internals.
Any proper way?

A: I thought of a way:
In MyItemRenderer::synchronize set the item's renderer to this. I don't like this very much, because it's abuse of synchronize, but it's certainly much better than mutable.

A: What about this?
QQuickFramebufferObject::Renderer* MyItem::createRenderer() const {
    return new MyItemRenderer();
}

More information here. At the end of this page, it is stated the following:

However, there is a special case when the FBO has to get recreated regardless: when moving the window to a screen with a different device pixel ratio. For example moving a window between a retina and non-retina screen on OS X systems will inherently need a new, double or half sized, framebuffer, even when the window dimensions are the same in device independent units. Just like with ordinary resizes, Qt is prepared to handle this by requesting a new framebuffer object with a different size when necessary. One possible pitfall here is the applications' caching of the results of the factory functions: avoid this. createFramebufferObject() and createRenderer() must never cache their return value. Just create a new instance and return it. Keep it simple.


text:
Q: Using PivotTable.js with aurelia and asp.net core My Project is setup based on ASP.Net Core with aurelia, as in this video by Rob Eisenberg https://channel9.msdn.com/Events/Build/2017/T6032
Now I'm trying to use PivotTable.js plugin with it.
It has an example function:
$(function () {
  $("#output").pivot(
    [
      { color: "blue", shape: "circle" },
      { color: "red", shape: "triangle" }
    ],
    {
      rows: ["color"],
      cols: ["shape"]
    }
  );
});

I tried it first in a simple html page with inline script tags and it worked fine.
In aurelia project, I wrap it in a load() function that gets triggered on a button click:
//playground.html
<button id="btn1" click.trigger="load()">Load</button>

............
//playground.ts
import $ from 'jquery'

export class Playground {
   load() {
    $(function () {
        $('#output').pivot(
    ...
   }
 }

I installed it with npm, now it looks like I'm having problem referencing it correctly. I tested with having it directly in the script tag of my viewmodel

It keeps throwing "pivot is not a function" error like below:
    jQuery.Deferred exception: __WEBPACK_IMPORTED_MODULE_0_jquery___default(...)(...).pivot is not a function app/components/play/playground/Playground.prototype.load/<@http://localhost:63822/dist/app.js?v=Co4Zys-nKtxDfRHuYeQtAcAzgXG9rRHqPqkwN0CzgJQ:27236:13

   mightThrow@http://localhost:63822    /dist/vendor.js?v=8kh55HdjmafGVyQfWaHURccoz4Vi-HAb9obSOc7CDCk:14851:21

     resolve/</process<@http://localhost:63822/dist/vendor.js?v=8kh55HdjmafGVyQfWaHURccoz4Vi-HAb9obSOc7CDCk:14919:12

     undefined
    vendor.js:15128:3
    TypeError: __WEBPACK_IMPORTED_MODULE_0_jquery___default(...)(...).pivot is not a function

My Index.cshtml seemed to look into dist folder for scripts so I moved the pivot.js files into dist and added script tags there

I have added jquery and jquery-ui as dependencies and devdependencies (I do have doubts whether this is correct way to do it) in package.json:
    "devDependencies": {
          "jquery": "^3.2.1",
          "jquery-ui": "^1.12.1"
          ....
     },
      "dependencies": [
       { "jquery": "^3.2.1" },
       { "jquery-ui": "^1.12.1" }
      ]

Also added a jquery as a plugin to webpack.config.js as suggested for some another plugin to make that work.
       plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        })

I tried adding cdn links to jquery in script tags in my viewmodel. None of these changes have changed the error message. How should I be referencing this and similar jquery plugins?

A: I fought a while to get pivottable.js work with webpack and Aurelia. You will need the following NPM packages:
jquery
jquery-ui-dist
pivottable

The "normal" jquery-ui package did not work for me.
In your typescript file, use the following imports:
import * as $ from 'jquery';
import 'jquery-ui-dist/jquery-ui';
import 'pivottable';

Then you can use the $('#output').pivotUI(...) function. In your template HTML file, you will need to import the CSS:
<require from="pivottable/dist/pivot.css"></require>

Using this setup and the same ProvidePlugin code, I am able to use pivottable.js within webpack without additional script tags.

A: you probably should add an import statement
import 'pivottable';
after the jquery import
if the npm package is right, this should do.
it is more of a webpack question than aurelia.
googling "webpack jquery pivottable" should get you more answers.


text:
Q: Three.js object moving to target I have a object that moves to a target. The problem is that the x position is quicker than the z position or the z position is quicker than the x position.
What can I do that my object slows down for the x position if the z position needs more time to move?
My code in the animation function:
var distanceX = objectX - targetX;
var distanceZ = objectZ - targetZ;

if( distanceX < 0) {
    visitor.translateX( 0.05 );
}else {
    if( distanceX > 0) {
        visitor.translateX( -0.05 );
    }
}

if( distanceZ < 0) {
    visitor.translateZ( 0.05 );
}else{
    if( distanceZ > 0) {
        visitor.translateZ( -0.05 );
    }
}

A: I would recommend to compute the current value as an absolute value instead of incrementally. What you are doing is basically something like this:
x = xLast + constantValue;

Instead, you could do this without needing the last value (this is called linear interpolation):
progress = Math.min((Date.now() - startTime) / duration, 1);
x = xStart + progress * (xEnd - xStart);

The progress value in this case is a value from 0 (animation start) to 1 (animation end).
If you write your animations like this, you can just set the duration for both parts to the same value. Using the three.js math utils you can even do this all at once:
var end = new THREE.Vector3(1, 0, 2);
var start = new THREE.Vector3(2, 0, -1);

// in animation-loop
var tmp = new THREE.Vector3();
var progress = Math.min((Date.now() - startTime) / duration, 1);

// tmp = progress * (end - start)
tmp.copy(end).sub(start).multiplyScalar(progress);
object.position.copy(from).add(tmp);

That way you will have all components of the position move at a constant speed that arrives at the destination exactly at the same time.
You might want to have a look at animation-libaries like tween.js. They can handle a lot of this quite comfortably.


text:
Q: Python Print each line of text file into list without \n I'm still new to learning python and was just wondering how to store each line of a text file into a list without the \n appearing.
I've tried:
file = open("test_file.txt", "r")
table = [line.split(') for line in file.readlines()]

Outputs:
[['Beans', ' 1222', ' 422', ' 6712\n'], ['Eggs', ' 4423', ' 122', ' 2231\n'], ['Tomato', ' 2232', ' 224', ' 2321']]

Desired output:
[['Beans', '1222', '422', '6712], ['Eggs', '4223', '122', '2231'], ['Tomato', '2232', '224', '2321']]

I've tried temp = file.read().splitlines() but it ends up storing it all into one list['Beans, 1222, 422, 6712', 'Eggs, 4423, 122, 2231', 'Tomato, 2232, 224, 2321']  when I still want each line to be a list itself.
Any help greatly appreciated!!

A: In my case, I always use following line to get rid of \n every time I read a file:
file = [line.strip("\n") for line in file.readlines()]

In your case, just use:
file = open("test_file.txt", "r")
table = [line.strip("\n").split(') for line in file.readlines()]

A: There's two quick solutions.
Since Yihua Zhou already provided one, I'll provide another. Please note that that the strip method might remove more than you want. Look at the docs for string.strip() here.
The splitlines() method splits a text on \n characters
with open("somefile.txt") as infile:
    table = [line.split() for line in infile.read().splitlines()]

Also note that if possible, you should use the with open() way to open files, as it closes it automagically. See this for some explanation...

A: It appears that your input file is in fact a CSV file where the spaces after commas are to be ignored, in which case you can use csv.reader with the skipinitialspace option for better readability:
import csv

with open("test_file.txt") as file:
    table = list(csv.reader(file, skipinitialspace=True))

Demo: https://replit.com/@blhsing/TechnicalPlumpMathematics


text:
Q: My Own Cascade Classifier: Can not get new positive sample. The most possible reason is insufficient count of samples in given vec-file I want to create my own cascade classifier to detect windows. I'm using Cascade Trainger Gui. I have 2805 positive images and 2718 negatives, but when I try to build my classifier then I get this error:

Can not get new positive sample. The most possible reason is
  insufficient count of samples in given vec-file.

I decreased my positive Image usage to 10 and min hit rate to 0,5 but this still isn't working.
Here is Github link with all files.


text:
Q: I cannot change the order of result columns in Windows Desktop Search 4.0 under Windows XP I cannot change the order of result columns in Windows Desktop Search 4.0 under Windows XP.
When I searched the web for how to do it, I found comments that under Windows Vista you could right-click the headers of the columns and tick them according to your needs or just drag them to the place you want, afterwards saving folder settings....
In my Windows XP I can tick columns and rearrange them in normal folders but any change to the columns in the Windows Desktop Search window seems prohibited. Nothing changeable.
Is that by design or is there a workaround?
Cheers.

A: Unfortunately I don't think it's possible on XP. Windows Desktop Search does not open in a regular Explorer window, although it looks similar to a "normal" folder.


text:
Q: Prove that $\lim_{x\to\infty} \frac{1}{x}\int_0^xf(t)dt$ exists and find it, where $f(t)$ is an alternating function. The problem: function $f$ alternates between $1$ and $-1$ on $[0^2; 1^2), [1^2; 2^2), ... [(n-1)^2; n^2)$, so on $[0^2; 1^2], \;f(x) = 1;$ on $[1^2; 2^2],\;f(x) = -1$ etc.
Prove that $\;\;\lim_{x\to\infty} \frac{1}{x}\int_0^xf(t)dt\;\;$ exists and find it.
What I did:

Questions: Where did I go wrong? I honestly don't believe this limit exists but it says so in the problem statement so I don't even know. I tried doing it without the $x \in \mathbb N$, but I get the same result: The limit can't exist because the value alternates between $1$ and $-1$. Thank you!

A: To fix your reasoning: The length of the $n$-th interval is $n^2 - (n - 1)^2 = 2n - 1$. Assume $x = n^2$, where $n \in \mathbb{N}$.
\begin{align}
\lim_{x \to \infty} \frac{1}{x} \int_0^x f(t) \, \mathrm{d}t &= \lim_{n \to \infty} \frac{1}{n^2} \int_0^{n^2} f(t) \, \mathrm{d}t \\
&= \lim_{n \to \infty} \frac{1}{n^2} \sum_{k = 1}^n (-1)^{k+1} (2k - 1) \\
&= \lim_{n \to \infty} \frac{1}{n^2} (-1)^{n+1} n \\
&= 0.
\end{align}

A: Let $x \in \mathbf R$. Then there is a unique integer $n \in \mathbf N$ such that $n^2 \le x < (n+1)^2$. We have
\begin{align*}
  \int_0^x f(t)\, dt &= \sum_{k=0}^{n-1} (-1)^k (2k+1) + (-1)^n(x-n^2)\\
    &= 2\sum_{k=0}^{n-1} (-1)^k k + \frac 12\bigl(1 + (-1)^{n}\bigr) + (-1)^n(x-n^2)\\
    &= \frac 12\bigl((-1)^{n-1}2n - 1\bigr) + \frac 12\bigl(1+(-1)^n\bigr) + (-1)^n(x-n^2)\\
\end{align*}
Dividing by $x$ now (note that $x \sim n^2$, this was your main mistake, if you let $x \in \mathbf N$, that is fine, but the sum goes up to $\sqrt x$ then, only), we have
\begin{align*}
  \def\abs#1{\left|#1\right|}\abs{\frac 1x \int_0^x f(t)\, dt}
  &\le \frac 12 \frac{2n + 1}x + \frac 1x + \frac{x-n^2}x
\end{align*}
Now $x-n^2 \le (n+1)^2 - n^2 = 2n+1$ and $\frac 1x \le \frac 1{n^2}$ as $n^2\le x$. Hence
\begin{align*}
   \abs{\frac 1x \int_0^x f(t)\, dt} &\le \frac 32 \frac{2n +1}{n^2} + \frac 1{n^2}
\end{align*}
Now $n \to \infty$ for $x \to \infty$, that is the above converges to $0$, therefore
$$ \frac 1x \int_0^x f(t)\, dt \to 0, \qquad x \to \infty $$


text:
Q: History of the Odd Dimensional Quantum Spheres After reading this question, I began to wonder about the history of quantum $(2N-1)$-spheres. Basically I have two questions:
(1) Who first introduced the $(2N-1)$-spheres, and who first introduced them as invariant subalgebras of quantum $SU_N$? I know that Podles is often credited with introducing quantum spheres, but as far as I can see (his paper is difficult to find on the web) he only introduced a family of deformations of $2$-spheres, which are not of course of the form $S^{2N-1}_q$. I know also that something appeared in the early FRT-papers, but these are also difficult to find, and are in Russian.
(2) The proof in Klimyk and Schmudgen of the generators and relations result is based on a 1993 paper by Noumi, Yamada, and Mimachi. (This is also difficult to find.) Was this the first generators and relations description for the for $S^{2N-1}_q$? Did it generalise an earlier result, ie for $S^5_q$?
P.S. I would also be very interested in hearing about the history of quantum projective spaces. Who first introduced them?  Who first introduced them as invariant subalgebras of quantum $SU_N$? Who first introduced them as invariant subalgebras of the quantum spheres?

A: (1)  I think Podles only introduced the quantum 2-spheres.  His paper is linked from MathSciNet, so you should be able to get it if you have access to ams.org.  I think the higher-dimensional spheres were first considered by Vaksman and Soibelman in http://www.ams.org/mathscinet-getitem?mr=1086447.  Unfortunately that paper, while it was translated into English, appears not to be available online.
(2)  Not sure, sorry.
About the projective spaces: I think http://www.ams.org/mathscinet-getitem?mr=1432197, by Dijkhuizen and Noumi, is one of the early papers, but they refer also to http://www.ams.org/mathscinet-getitem?mr=1183477
 by Korogodsky and Vaksman, which I haven't really looked at but seems to contain some relevant stuff.  And really the paper by Noumi et al is quite early.  I'm not sure about who first thought about them as invariant subalgebras of the quantum spheres.