text:
Q: Hibernate cant find the correct foreign key I am having a problem that hibernate tries to drop foreign keys that dont exist instead of the one that exists. My scenario looks like this.
I want to run a junit tests, before ever test I want to create DB and after ever test I want to drop it. For that I use hibernate create-drop property. However the tricky part is that I want to create my own tables as a way to test newly added sql and verify that it will run fine once I deploy it to the production db server. So what happens is this

*

*Hibernate creates tables automatically

*Hibernate creates foreign key relationships

*Hibernate runs my drop table scripts (that succeeded since there is no data so no foreign key rule has been broken)

*Hibernate runs my create table scripts

*Hibernate runs my add foreign constraint scripts

*Hibernate runs my insert data scripts

*Test is executed

*Hibernate tries to remove the foreign key and it fails.

The reason hibernate has not be able to remove it is cause it tried to remove that one that hibernate created and not the one that was created by my scripts.
Any idea how to force hibernate to find out the actual foreign key? Any way to get around this problem?
Thanks everyone
Class for which hibernate creates the table
TodoGroup.java
@Entity
@Table(name = "ToDoGroups")
public class ToDoGroup implements Serializable{

    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "Name", length = 50)
    private String name;
    @ManyToOne
    @JoinColumn(name = "UserSettingsId")
    @XmlTransient
    private UserSettings userSettings;
    @OneToMany(mappedBy = "group", cascade = CascadeType.ALL)
    private List<ToDoItem> items;

hibernate adding the constraint
alter table ToDoGroups
        add constraint FK790BA1FAFE315596
        foreign key (UserSettingsId)
        references UserSettings

running my own tables that work fine since there is no data so I can remove what hibernate created in order to verify my sql
DROP TABLE IF EXISTS ToDoGroups;

CREATE TABLE ToDoGroups (ID BIGINT NOT NULL IDENTITY, Name VARCHAR(50) NOT NULL, UserSettingsId BIGINT NOT NULL, PRIMARY KEY (ID));

ALTER TABLE ToDoGroups ADD FOREIGN KEY (UserSettingsID) REFERENCES UserSettings (ID);

drop fk it tries to execute
alter table ToDoGroups drop constraint FK790BA1FAFE315596
java.sql.SQLException: Constraint not found FK790BA1FAFE315596 in table: TODOGROUPS in statement [alter table ToDoGroups drop constraint FK790BA1FAFE315596]

tries to remove the table which fails due to the constrain that I have set in my create.sql script
    drop table ToDoGroups if exists
java.sql.SQLException: Table is referenced by a constraint in table SYS_REF_SYS_FK_808_810 table: TODOITEMS in statement [drop table ToDoGroups if exists]

Update
I have also noticed that hibernate when it first starts before it creates the tables (so this is way before my scripts are run), tries to remove foreign key in order to drop any table that exists.
So how does hibernate know what foreign key to use? It uses the same key that
first statement it executes
alter table ToDoGroups drop constraint FK790BA1FAFE315596

then it drops all of the tables
drop table ToDoGroups if exists

then it creates table
create table ToDoGroups (
    id bigint generated by default as identity (start with 1),
    Name varchar(50),
    UserSettingsId bigint,
    primary key (id)
)

then it adds the same FK
alter table ToDoGroups
    add constraint FK790BA1FAFE315596
    foreign key (UserSettingsId)
    references UserSettings

I think my question here is how does hibernate know what FK to use. It used the same FK in the first drop statement when there was even no table. Later it used that some FK to create the relationship. Shouldn't hibernate first check if the table exists and then tries to determine what is the FK?

A: As far as I understand, your problem is that your own script and hibernate don't use the same constraint name.
You can specify a constraint name used by hibernate with this annotation on your relationship:
@ForeignKey(name = "fk_UserSettings")

And additionally, in your create.sql:
ALTER TABLE ToDoGroups ADD CONSTRAINT fk_UserSettings FOREIGN KEY (UserSettingsID) REFERENCES UserSettings (ID);

I think my question here is how does hibernate know what FK to use. It used the same FK in the first drop statement when there was even no table. Later it used that some FK to create the relationship. Shouldn't hibernate first check if the table exists and then tries to determine what is the FK?

The foreign key name used by hibernate is the concatenation of
"FK_" + hashcode of referenced entity name + hash code of referenced columns name on that entity.

So it is not a randomly generated key (you will see that it will change if you change your entity name). And that's how hibernate knows the name of the fk to drop (hibernate is expecting that the constraint was created by hibernate with this well known naming strategy).
Hibernate use the name of the constraint to manipulate it. It don't compare the "rule" coded in constraints associated with a table to see if the constraint is already there or not.


text:
Q: java pie chart height is not properly placed I am using JFreeChart to make a chart in my program. My problem is I cannot set the height properly. I have tried every command I could think of, I have put it in other panels, however, nothing works.
I want to be able to put it somewhere in a corner...or anywhere really and to be able to set both width and height. I have also tried with setPrefferedSize, but it only works with width.
Code :
DefaultPieDataset result = new DefaultPieDataset();
    result.setValue("TotalSwag", totalSwag);
    result.setValue("TotalYolo", totalYolo);
    result.setValue("TotalCool", totalCool);
    result.setValue("TotalLame", totalLame);
    JFreeChart chart = ChartFactory.createPieChart3D("Swag-O-meter", result, true, true, false);
    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    ChartPanel chartPanel = new ChartPanel(chart, W, H, W, H, W, H,
            false, true, true, true, true, true);
    chartPanel.setMaximumSize(new Dimension(150, 150));

    charPanel.add(chartPanel);
    charPanel.setSize(W, H);
    contentPane.add(charPanel, BorderLayout.WEST);

A: A JFreeChart is not a JComponent, but a ChartPanel is. You can control the size using any appropriate approach mentioned here.

I'd like all windows to be the same size.

In this case, I'd override getPreferredSize() to return a Dimension having equal width and height. You can use PiePlot#setCircular() to preserve the aspect ratio of the PiePlot.
This example shows a GridLayout(1, 0) of charts each having a ThermometerPlot:

A: I have found how to fix it, all I had to do is not use a flowLayout, but a grouplayout, since the panel was making the chart be enlarged, just like if you'd put a button in a flowLayout it would become the size of it's containing zone. Thank you everyone for the amazing help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intra-rater reliability of an instrument I'm working on the implementation of a "new version" of an existing instrument in the posture analysis.
I know that if I want to compare the measures between the old one and the new one I can use Bland-Altman plot, but what I'm trying to do is assess the reliability of this instrument by comparing the measures collected twice.
I mean, something like the intra-rater. Do you think is correct to use this approach since I'm evaluating the outcomes of the instrument and not the rater?


text:
Q: A Workflow Foundation 4 argument of a nested type One of the arguments to my workflow (xaml) is a nested type declared in a static class. Unfortunately, the "Browse for .NET type" dialog box does not show me this type irrespective of what I search for
full.namespace.containingstaticlass.typeIneed
or
full.namespace.containingstaticlass+typeIneed
Since the dialog didn't work, I tried editing the xaml itself but couldn't figure out how to define the
Type="InArgument(xmlnamespacetomyassembly:???)"
Help!?
Edit: It seems the Workflow Designer does not work with nested types at all, because an expression to cast an object to a nested type gave me this error.

At this point, any workarounds will be most welcome!
Added a simple sample that shows the problem.

*

*There is no way to add a parameter (in the designer) of type NestedType.EssentialStruct

*Even if you add an expression to cast Object to NestedType.EssentialStruct in the properties window against any InArgument, the designer will complain.

Posting the relevant sections also:
The nested type that needs to be used in the CodeActivity
public static class NestedTypes
{
    public struct EssentialStruct
    {
    }
}

A simple activity that uses the nested type as an InArgument and result
public sealed class TestActivity : CodeActivity<NestedTypes.EssentialStruct>
{
    public InArgument<NestedTypes.EssentialStruct> Handle
    {
        get;
        set;
    }

    protected override NestedTypes.EssentialStruct Execute(CodeActivityContext context)
    {
        return context.GetValue(this.Handle);
    }
}

I can't post the XAML that produces the error because the designer doesn't save it, errors out just before saving it.

A: You need to use import on the workflow. It's a tab in the designer. It's next to variables and arguments.

A: Check that the referenced assembly is built in x86 (or Any CPU). I had the same problem and it turned out that the referenced DLL was x64 which made it so the Visual Studio designer couldn't see it.


text:
Q: Insert greater/less than or equal symbol into db2 table column my clients copy and paste greater or less than symbol from Microsoft Word into my Java web application. I use IBM DB2 database. But the symbol shows in empty squeare in my select result.
What have I tried?
Inserting greater/less than or equal symbol into SQL Server database
I tried above link, insert some value but it didn't insert value.
I thought I can replace that sign with >=  but I don't want to struggle. So how can I achieve this problem?


text:
Q: assign argument when calling a function in actionscript var callback = null;
addEventListener(Event.MouseDown, callback = function(e:Event){blabla....});

Can I assign arguments when calling a function?

A: Of course. Try it this way instead.
var callback = function(e:Event, arg1, arg2) { blabla....};

addEventListener(Event.MouseDown, function(e) {  callback(e, 0, 1); } );

Or If I misunderstood your question, perhaps this way:
var callback = null;

addEventListener(Event.MouseDown,

       callback = function(e:Event) { anotherfunction(arg1, arg2); });


text:
Q: Show Monthly Revenue By EmployeeID I have a database with sale data for the past 5 years, 2012 - current.  I am in need of showing a breakdown by employeeID and the monthly sale amount.  I know this syntax will work, but it is going to be quite cumbersome to add a new case statement every time we roll into a new month.  Is there a quicker/more efficient way to accomplish this?
This is sample DDL (sample as it is only a very few rows)...
Declare @Monetary Table(empID varchar(10), empsaleamt float, empsaledate date)
Insert Into @Monetary (empID, empsaleamt, empsaledate) Values
('123abc', 100.00, '20160101'), ('123abc', 200.00, '20160101'), ('123abc', 300.00, '20160201')
,('456cde', 200.00, '20160101'), ('456cde', 100.00, '20160201'), ('456cde', 100.00, '20160301')

Select
empID
,Sum(case when (Year(empsaledate) = '2016' AND Month(empsaledate) = '01') Then empsaleamt Else 0 End) As Jan16Sales
,Sum(case when (Year(empsaledate) = '2016' AND Month(empsaledate) = '02') Then empsaleamt Else 0 End) As Feb16Sales
,Sum(case when (Year(empsaledate) = '2016' AND Month(empsaledate) = '03') Then empsaleamt Else 0 End) As Mar16Sales
FROM @Monetary
Group By empID
ORDER By empID ASC

A: You could consider to use a PIVOT solution:

Declare @Monetary Table(empID varchar(10), empsaleamt float, empsaledate date)
Insert Into @Monetary (empID, empsaleamt, empsaledate) Values
('123abc', 100.00, '20160101'),
('123abc', 200.00, '20160101'),
('123abc', 300.00, '20160201'),
('456cde', 200.00, '20160101'),
('456cde', 100.00, '20160201'),
('456cde', 100.00, '20160301'),
('123abc', 100.00, '20170101'),
('123abc', 200.00, '20170101'),
('123abc', 300.00, '20170201'),
('456cde', 200.00, '20170101'),
('456cde', 100.00, '20170201'),
('456cde', 100.00, '20170301');

SELECT ID, [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]
FROM
    (SELECT CONCAT(empId,'-',CAST(YEAR(empsaledate) AS varchar(10))) as ID,
            month(empsaledate) AS months, empsaleamt
     FROM   @monetary ) src
PIVOT
    (SUM(empsaleamt) FOR months IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) pvt;

GO

ID          |   1 |   2 |    3 |    4 |    5 |    6 |    7 |    8 |    9 |   10 |   11 |   12
:---------- | --: | --: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---:
123abc-2016 | 300 | 300 | null | null | null | null | null | null | null | null | null | null
123abc-2017 | 300 | 300 | null | null | null | null | null | null | null | null | null | null
456cde-2016 | 200 | 100 |  100 | null | null | null | null | null | null | null | null | null
456cde-2017 | 200 | 100 |  100 | null | null | null | null | null | null | null | null | null

dbfiddle here


text:
Q: AMD Ryzen 5 3400G on Linux Ubuntu 18.04 (HDMI fails at 60 Hz refresh rate) I just bought a new 3400G (AMD Ryzen 5 3400G with Radeon Vega 11 Graphics) and the 60 Hz refresh configuration is not working via HDMI. At 30 Hz all works ok, but when I put 60Hz on refresh rate at 3840x2160 the hdmi signal randomly disapears and then reappear, or it shows random ghost lines on the TV.
The HDMI cable work OK with other devices and support HDMI 2.0. It is the first time that I use 4k at 60Hz on a device. In particular this device is a RCA TS50UHD Smart TV.
I do not tried yet with the steps on https://askubuntu.com/a/1168404/142926. Anyone know if I follow the steps of link above Can I "crash" something, or that option only add an option to grub menu and I can use an older kernel installed for boot in order to go back and use the system with 30 Hz ithout a problem
My actual kernel and Ubuntu version:
➜  default uname -a
   Linux L-G580 5.0.0-31-generic #33~18.04.1-Ubuntu SMP Tue Oct 1 10:20:39 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
➜  default lsb_release -a
   No LSB modules are available.
   Distributor ID:  Ubuntu
   Description: Ubuntu 18.04.3 LTS
   Release: 18.04
   Codename: bionic

 06:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Picasso [1002:15d8] (rev c8) (prog-if 00 [VGA controller])

glxinfo | grep OpenGL
OpenGL vendor string: X.Org
OpenGL renderer string: AMD RAVEN (DRM 3.27.0, 5.0.0-31-generic, LLVM 8.0.0)
OpenGL core profile version string: 4.5 (Core Profile) Mesa 19.0.8
OpenGL core profile shading language version string: 4.50
OpenGL core profile context flags: (none)
OpenGL core profile profile mask: core profile
OpenGL core profile extensions:
OpenGL version string: 4.5 (Compatibility Profile) Mesa 19.0.8
OpenGL shading language version string: 4.50
OpenGL context flags: (none)
OpenGL profile mask: compatibility profile
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 3.2 Mesa 19.0.8
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20
OpenGL ES profile extensions:

I appreciate any help....
Thank You.


text:
Q: Three.js models loading issue I'm trying to load gltf model into my page using the following code :

            var loader = new THREE.GLTFLoader().setPath('models/football_goal/' );
            loader.load('scene.gltf', function (gltf) {
                gltf.scene.traverse( function( node ) {
                 if ( node instanceof THREE.Mesh ) { node.castShadow = true; }
                } );

The problem is when the I open the page the browser fail loading the model and downloading the scene.bin file instead.
This is only on my device and other collaborators don't have this issue.


text:
Q: Angular - Get array from JSON file Sorry for the noob question but I am just getting started with Angular. I have this array declared in services.js:
var articles = [{
    id: 1,
    title: 'Article 1 Title',
    intro: 'Article 1 Intro',
    image: 'photo.jpg',
    published: '27/10/2016',
    text: 'Article 1 Text',
    url: 'http://www.domain.com'
  }, {
    id: 2,
    title: 'Article 2 Title',
    intro: 'Article 2 Intro',
    image: 'photo.jpg',
    published: '27/10/2016',
    text: 'Article 2 Text',
    url: 'http://www.domain.com'
  }];

Now that everything works fine in my Angular App I want to read this array from a JSON file that can be found, for example, at www.domain.com/articles.json and it looks like this:
{
  "articles": [
    {
      "id": 1,
      "title": "Article 1",
      "intro": "Article 1 Intro",
      "image": "image.png",
      "published": "27/10/2016",
      "text": "Article 1 Text",
      "url": "http://www.domain.com/article-1"
    },
    {
      "id": 2,
      "title": "Article 2",
      "intro": "Article 2 Intro",
      "image": "image.png",
      "published": "27/10/2016",
      "text": "Article 2 Text",
      "url": "http://www.domain.com/article-2"
    }
  ]
}

How can I make this change?

A: To get the data of the file in your Angular app, you'll have to get the file's contents through an HTTP request. The easiest way to do this is by using the $http service.
Example (with relative url):
$http.get('/articles.json').then(function (response) {
    var articles = response.data.articles;

    // Do something with articles...
});

The callback function you're passing to the then method will be called when the HTTP request was successful. Note that your data will only be available in this callback function. Also don't forget to include a dependency to the $http service in your controller. ;)


text:
Q: How to reach local sites in chrome If I try to get onto my local media server in chrome, which has an address such as ' openelec ' or '12.234.12.5' it will just google whatever I type in to the address/search bar. How can I temporarily avoid this normally helpful feature to access these services in chrome?

A: Try to add http:// before the address.

A: Even simpler than typing http:// before the address, you can usually type / after it:
openelec/
12.234.12.5/


text:
Q: Can you use substitution, then by parts when integrating? How do you integrate $2x/(2x-1)^2$ ?
I'm told to use the substitution $u=2x-1$
I get to 0.5 X "integral of" (u+1)/u^2 and then I do it by parts...
This leads me to a solution with x's but no logs which is what wolfram alpha tells me is correct...
What have I missed? Any help is appreciated thanks

A: Let $u=2x-1$; $dx=\frac{1}{2}\,du$. The integral is:
$$\frac{1}{2}\int \frac{u+1}{u^2}\, du=\frac{1}{2}\int\left(\frac{1}{u}+\frac{1}{u^2}\right)du$$
$$=\frac{1}{2}\left(\int\frac{1}{u}\,du+\int\frac{1}{u^2}\,du\right)=\frac{1}{2}\left(\ln|u|-\frac{1}{u}\right)+C$$
You can do it by parts, but it's not worth it. The integral $\int\frac{P(x)}{Q(x)}dx$, where $P(x),Q(x)$ are polynomials, can always be computed similarly (you may need to apply the "Partial Fractions" method).

A: Of course it's okay to combine substitution and integration by parts. Since in essence, your question is "Why do I get a different solution than Wolframalpha?", I'll answer that.
In short, if your answer doesn't involve logarithms, it is (most likely) wrong. Since I can't comment on your try (as you didn't provide it), I'll show how I would do it with substitution and integration by parts.
Let $u=2x-1$ and use substition:
$$\int \frac{2x}{(2x-1)^2} dx=\frac{1}{2}\int \frac{u+1}{u^2} du$$
Let $f(u)=u+1, g'(u)=u^{-2}$ and use integration by parts:
$$\begin{align}\frac{1}{2}\int f(u)g'(u) du&= \frac{1}{2}\left((f(u)g(u) - \int f'(u) g(u)du\right)=\frac{1}{2}\left( (u+1)\frac{1}{-u}-\int -\frac{1}{u} \cdot 1 du\right)\\
&=\frac{1}{2}\left(-\frac{u+1}{u}+\ln |u|\right)=\frac{1}{2}\left(-\frac{1}{u}+\ln|u|\right)-0.5\end{align}$$
So including the constant and absorbing $-0.5$ into it, we get
$$ \frac{1}{2}\left(-\frac{1}{u}+\ln|u|\right)+C$$
You can now resubstitute $u=2x-1$.
Notes: Of course you can switch $f$ and $g$ above. If you used it as above, this probably helps to find your mistake. If not, please provide your computation. Also, this might not be the most elegant or most straightforward way to find that integral, see the answer by user236182.


text:
Q: My client won't reload after ajax put even with .then and location.reload I can't get the client to console.log or reload after this ajax PUT. The put goes through to the database fine. I just need it to reload to see the new results.
$(".devour").on("click", function(event) {
  event.preventDefault();
  var id = { id: $(this).attr("id") };

  $.ajax("/", {
    type: "PUT",
    data: id,
  }).then(function() {
    console.log("Updated Burger");
    location.reload();
  });
});

A: can you try like this
$.ajax({
        type: 'PUT',
        url: 'http://example.com/api',
        contentType: 'application/json',
        data: JSON.stringify(data), // access in body
    })
    .then(
          ()=>console.log("success"),
          ()=>console.log("FAIL"));//check for fail may be issue

or try more explicit order way
    $.ajax({
        type: 'PUT',
        url: 'http://example.com/api',
        contentType: 'application/json',
        data: JSON.stringify(data), // access in body
    }).done(function () {
        console.log('SUCCESS');
    }).fail(function (msg) {
        console.log('FAIL');
    }).always(function (msg) {
        console.log('ALWAYS');
    });


text:
Q: Shopify enter password field I am creating my Shopify store right now, and I don't know how to add 'enter password' field on password page. I tried many codes that I've found in internet, but nothing has worked as for now.
Could anybody please help me?

A: Your Question seems not clear,
However you might be facing issue to enable customer registration.
if yes follow below step:
Go to Settings => Checkout
And check below option as shown in the screenshot.


text:
Q: iOS Can't Get PDF to Appear in UIWebView I'm having issues displaying a PDF in a UIWebView - something that should be really trivial (even for me beginner level). However I'm not seeing anything.
I have a UIWebView correctly connected as an IBOutlet, then in the viewDidLoad, i have the following code:
NSURL *targetURL = [NSURL URLWithString:@"/Users/tom........../PDF_6.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[_pdfWebView loadRequest:request];

Any ideas what I'm doing wrong??
Thanks.
(Apologies if this is a really duplicated question i just can't find the answer).

A: Since it seems you want to load the PDF from a file, you need to create a file URL:
NSURL *targetURL = [NSURL fileURLWithPath:@"/Users/tom........../PDF_6.pdf"];

BTW - that path is only going to work in the simulator, not on a real iOS device.


text:
Q: Unknown PTR record in DNS; it's not there in Cloudflare DNS Settings (1.) There is an extra, unwanted, unexpected, unadded PTR record in my DNS settings, with value set to the Domain Name "mediati.net". You can see it here in MxToolbox Reverse Lookup:
MxToolbox shows unwanted PTR TXT record
(2.) cPanel also notices and complains about the extra PTR record:
cPanel also complains about the extra PTR record
(3.) Yet my DNS records in Cloudflare only have one PTR TXT record, the one I want.
DNS Records in Cloudflare
I haven't found anyone else with this same problem. Where could the PTR record to "mediati.net" be coming from !??
Paul

A: I do not know why that PTR record existed, nor why it did not reflect what was in my Cloudflare DNS settings; however, my ISP was able to remove/change that PTR record for me.
That is some strange DNS record that I don't have control over.
Additional thoughts welcome here, but the current fix is that you can't fix it, you need your provider to fix it.


text:
Q: The high OS version validation detected when copy the database I have an application that copies the database from the local package to the local folder. After I create the app package to the store and test using Windows App Cert Kit, an error message will appear as shown below:

And after I try to install using powershell, then when the application is first opened, the application runs smoothly. But after the application is closed, then run again, then only the splash screen appears.
Code:
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Tryout.sqlite"));
if (!CheckFileExists("Tryout.sqlite").Result)
            {
                CopyDatabase();
            }
public async void CopyDatabase()
        {
            StorageFile dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Tryout.sqlite"));
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            await dbFile.CopyAsync(localFolder, "Tryout.sqlite");
        }

        private async Task<bool> CheckFileExists(string fileName)
        {
            try
            {
                var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                return true;
            }
            catch (Exception ex)
            {
            }
            return false;
        }

Here the project
How to handle it?

A: I have tested your code, the problem is you have used async in App constructor method, this will cause thread blocking. For checking file exist, you could use File.Exists sync method to avoid thread blocking. I have edit your code please check.
public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    if (!CheckFileExists("Tryout.sqlite"))
    {
        CopyDatabase();
    }

}

private bool CheckFileExists(string fileName)
{
    bool isExist;
    isExist = File.Exists(Path.Combine(ApplicationData.Current.LocalFolder.Path,fileName)) ? true : false;
    return isExist;
}


text:
Q: Should'nt I git ignore cdk.out folder which is made by AWS CDK? AWS CDK create cdk.out project root. I don't know if I should add git files.

A: There is no need to add cdk.out to git. It just holds artifacts like synthesized cloudformation templates which do not need to be in version control.

A: If you use cdk init app, you see that cdk.out folder is in .gitignore.
*.js
!jest.config.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out


text:
Q: Flow.take(ITEM_COUNT) returning all the elements rather then specified amount of elements I've a method X that's getting data from the server via pub sub. This method returns a flow. I've another method that subscribes to the flow by method X but only wants to take the first 3 values max from the flow if the data is distinct compared to previous data. I've written the following code
fun subscribeToData() : Flow<List<MyData>> {
    ....
    //incoming data
    emit(list)
}

fun getUptoFirst3Items() {
   subscribeToData()
   .take(ITEM_COUNT) // ITEM_COUNT is 3
   .distinctUntilChange() //only proceed if the data is different from the previous top 3 items
   .mapIndex {
     //do transformation
   }
   .collect { transformedListOf3Elements ->

   }

}

Problem:
In collect{} I'm not getting 3 elements but rather I'm getting all the data that's coming in the flow.
I'm not sure what's wrong here? Can someone help me?

A: You have a Flow<List<MyData>> here, which means every element of this flow is itself a list.
The take operator is applied on the flow, so you will take the 3 first lists of the flow. Each individual list is not limited, unless you use take on the list itself.
So the name transformedListOf3Elements is incorrect, because the list is of an unknown number of elements, unless you filter it somehow in the map.

A: @Joffrey answer already explained why you get the whole list returned and suggested you use take() on the list itself.
If you want to take just the first ITEM_COUNT elements from every list that is emitted/observed, then you have to map the result and only take ITEM_COUNT items from the list each time, instead of taking ITEM_COUNT items from the flow.
fun getUptoFirst3Items() {
   subscribeToData()
   .map {
     // in Kotlin stdlib Iterable<T> has an extension method take(n: Int)
     // that will return a List<T> containing the first n element from the iterable
     it.take(ITEM_COUNT)
     // alternatively you can also use subList, but the semantics are not the same,
     // so check the subList documentation, before using it
     it.subList(0, ITEM_COUNT)
   }
   .distinctUntilChange() //only proceed if the data is different from the previous top 3 items
   .mapIndex {
     //do transformation
   }
   .collect { transformedListOf3Elements ->

   }

}


text:
Q: Can a function with four fractions be solved? $g(x^2+{\sqrt {x}})$ when $g(t) = \frac{8}{t}-6t$.
I have $\frac{8}{x^2} - \frac{6x^2}{1} + \frac{8}{\sqrt{x}} - \frac{6}{\sqrt{x}}$.
What next?

A: Hint: What you have here is not $g\bigl(x^2+\sqrt x\bigr),$ but rather $g\bigl(x^2\bigr)+g\bigl(\sqrt x\bigr).$ Do you see why?
You cannot "split apart" the problem, as you seem to want to do. To see why, let's consider the case that $x=1$. On the one hand, $1^2=1$ and $\sqrt1=1,$ so when $x=1$ we have $$g(x^2)=g(1)=\frac81+6\cdot1=8+6=14,$$ and similarly $g(\sqrt x)=g(1)=14,$ so $$g\bigl(x^2\bigr)+g\bigl(\sqrt x\bigr)=14+14=28.$$ However, $$g\bigl(x^2+\sqrt x\bigr)=g(2)=\frac82+6\cdot 2=4+12=16,$$ which isn't the same at all!
The mistake you're making is a very common one for people to make when first meeting function notation--after all, we can distribute multiplication like $2(x+y)=2(x)+2(y),$ so shouldn't we be able to distribute $g(x+y)=g(x)+g(y)$? Unfortunately, the answer is "no," in general. Think of the function $g$ not as a number, but more as a machine--in thus case, if you stick an appropriate $t$ into one end of the function, it spits $\frac8t+6t$ out the other end. We abbreviate this output with the label "g(t)"; it just means put $t$ into $g$ and see what pops out.
And just as with machines, it sometimes makes a difference when and how you put things in. For example, say our machine heated something significantly for ten minutes while stirring it. If we added water and soup mix together, then put it in our machine, we could end up with hot soup. If we put them in our machine separately and then added the results together, we'd end up with charred soup mix drifting in water!

A: $g(t) = \frac 8t - 6t\\
g(x^2 + \sqrt x) = \frac 8{x^2 + \sqrt x} - 6(x^2 + \sqrt x)$
And I would be content to say that you are done here.  There really isn't much reason to keep simplifying.  Nor is there anything to "solve."
As for the rest of what you have...
 you cannot split up the fraction.  i.e.
$\frac 8{x^2 + \sqrt x} \ne \frac 8{x^2} + \frac 8{\sqrt x}$


text:
Q: Adding Bank Account in Stripe.NET for Managed Account I've searched through the documentation on both the Stripe website and JaymeDavis' GitHub and still cannot manage to figure out if I'm correctly creating a bank account for a managed stripe account.  From Stripe's website, it's clear this is what I need...
curl https://api.stripe.com/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts \
   -u sk_test_xxxxxxxxxxxxxxxxxxxxxx: \
   -d external_account=btok_xxxxxxxxxxxxxxxxxxx

I have the token (btok....) returned from Stipe.js, and I have the account ID used in the curl link for the managed account, as well as the secret key.  However, I cannot figure out what the process is to execute this in C#
My guess so far has been:
    //Sample code for creating a managed account
    StripeAccountService stripeAccountService = new StripeAccountService();
    StripeAccountCreateOptions managedAccountCreateOption = new StripeAccountCreateOptions();
    managedAccountCreateOption.Managed = true;
    managedAccountCreateOption.Country = "US";

    StripeRequestOptions connectAccountRequest = new StripeRequestOptions();
    connectAccountRequest.ApiKey = ConfigurationManager.AppSettings["StripeApiKey"];
    Stripe.StripeAccount response = stripeAccountService.Create(managedAccountCreateOption, connectAccountRequest);

    // ADD Bank Account
    var myAccount = new StripeAccountUpdateOptions();
    myAccount.ExternalBankAccount.TokenId = "SampleToken";

    var accountService = new StripeAccountService();
    Stripe.StripeAccount bankAccount = accountService.Update(response.Id, myAccount);

The problem I'm having here is with adding the bank account.  I want to create the bank account separately so that I can save the last 4 digits of a card/bank account (non-sensitive data) used in payouts in our database.  The way above simply adds a single bank account to the managed user, and will not work as I would like to add multiple bank accounts for payouts.  Any sample code in adding a bank account to an already existing managed account would help immensely (i.e. create a bank account with the token returned from Stripe.js, then in a separate action add this bank account to the managed user account so that I can grab the last 4 digits of this bank account as well as any additional accounts that are added in this way in the future). Thank you in advance for your help and time!

A: You can just retrieve a Managed Account instead of creating one, i.e.:
StripeAccount response = accountService.Get(accountId);
From there you can add additional Bank Accounts.  The result of that API call is a BankAccount, and you should be able to access the last4 from there.


text:
Q: How do I replace separator of breadcrumb in react-bootstrap using css? so I have a breadcrumb component that I've used with react-bootstrap. I need to override the default separator with ">". But it did not override anything. Could anyone help with this?
Breadcrumb:
<Breadcrumb>
   <Breadcrumb.Item onClick={goTo('/')}>Home</Breadcrumb.Item>
   <Breadcrumb.Item onClick={goTo(`/store`)}>
      {store?.name || 'unknown'}s
   </Breadcrumb.Item>
   <Breadcrumb.Item active>{title}</Breadcrumb.Item>
</Breadcrumb>

CSS:
.breadcrumb-item+.breadcrumb-item::before { content: ">" !important; }

A: .breadcrumb-item+.breadcrumb-item::before{content:var(--bs-breadcrumb-divider,">") !important ;}

A: you can do it like this
.breadcrumb-item + .breadcrumb-item::before {
  content: "|" !important;
}

I am  using this code and its working
.breadcrumb-item {
  + .breadcrumb-item::before {
    content: ">" !important;
    align-self: baseline;
    color: #7d8daa;
  }
}

PS : Please make sure that there is no conflicting font-family to the selector else it might not work as expected.

A: You can use styled-components
like that
import React from "react";
import { Breadcrumb } from "react-bootstrap";
import styled from "styled-components";
const StyledBreakcrumb = styled(Breadcrumb.Item)`
  &:not(:first-child):before {
    content: ">" !important;
  }
`;
function BreadcrumbBs() {
  return (
    <>
      <Breadcrumb>
        <StyledBreakcrumb href="www.google.com">Home</StyledBreakcrumb>
        <StyledBreakcrumb href="www.google.com">Library</StyledBreakcrumb>
        <StyledBreakcrumb active>Data</StyledBreakcrumb>
      </Breadcrumb>
    </>
  );
}

export default BreadcrumbBs;


text:
Q: Spring Boot ControllerAdvice TimeoutException Not Caught I have multiple ExceptionHandler in controllerAdvice. one for TimeoutException and other for Exception classes.
When i throw new TimeoutException, it gets caught in Exception Handler not in TimeoutException Handler
below is the code:
@ControllerAdvice
public class CoreControllerAdvice {

     @ExceptionHandler(value = { Exception.class })
     @ResponseBody
     public ResponseEntity<ErrorResponse> handleException(Exception ex) {

        log.info("handleException", ex);
     }

     @ExceptionHandler(value = { TimeoutException.class })
     @ResponseBody
     public ResponseEntity<ErrorResponse> handleTimeoutException(Exception ex) {

        log.info("handleTimeoutException", ex);
     }
}

I throw Exception as
throw new TimeoutException("test");

Can some one help, why it is not caught by TimeoutException Handler
Thanks,

A: The parameter in the method handleTimeoutException seems incorrect to me, instead of Exception it should be TimeoutException.
 @ExceptionHandler(value = { TimeoutException.class })
 @ResponseBody
 public ResponseEntity<ErrorResponse> handleTimeoutException(TimeoutException ex) {

    log.info("handleTimeoutException", ex);
 }


text:
Q: Foundation Magellan starts sticking too early or too late after browser is resized Mainly my issue is that Magellan starts sticking too early or too late after scaling the browser window. At first load everything works before resize and also when resized after page is refreshed.
When downscaling browser window the automatic treshold is still using the "initial" calculated treshold from the larger viewport that was first loaded. I've tried creating an event binding to window.resize and then setting the treshold again to 0 and calling reflow and set_expedition_position, it makes it slightly better but doesnt fix the issue.
Specifying a value for treshold has no significant effect.
My settings:
$(document).foundation({
    "magellan-expedition": {
        active_class: 'active',
        threshold: 0,
        destination_threshold: 0,
        throttle_delay: 50,
        fixed_top: 70,
        offset_by_height: true
    }
});

Image of too early sticking magellan after resize, the bar above is the one that should be sticking only after the bar below.

A: This wasn't actually just a bug with magento but instead was the cause of multiple different issues. I'm unable to reproduce this anymore.


text:
Q: How can I specify start date and end date when loading events in fullcalendar? I'm loading the events using:
events: {url: "url" }

"url" return json data.
What I want to do is to specify the start and end parameters of this url (Fullcalendar specify them to the current date).

A: Do you mean:

events: {
        url: '/myfeed.php',
        type: 'POST',
        data: {
            startDate: 'someDate',
            endDate: 'someEndDate'
        },
        error: function() {
            alert('there was an error while fetching events!');
        }
    }

Ref: FullCalendar


text:
Q: Scene Delegate doesnt update View Controller How do i achieve this code in Scene Delegate
  // App Delegate
 func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return SCSDKLoginClient.application(app, open: url, options: options)
    }

Because I need to get some data from the callback. Currently, the callback won't trigger the App Delegate. Imagine that the callback is an OAuth flow.
I found a solution but it didn't work well
// Scene Delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else {
            return
        }

        SCSDKLoginClient.application(UIApplication.shared, open: url, options: nil)
     }

because I need to pass options value to this scene. How would I achieve AppDelegate method in Scene Delegate?

A: If the problem is how to pass the options param, try the following code. Basically UIOpenURLContext has two members variables url and options, you have to map that ApplicationDelegate options.
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let urlContext = URLContexts.first else {
            return
        }

        let url = urlContext.url

        let options: [UIApplication.OpenURLOptionsKey : Any] = [
            UIApplication.OpenURLOptionsKey.annotation : urlContext.options.annotation as Any,
            UIApplication.OpenURLOptionsKey.sourceApplication : urlContext.options.sourceApplication as Any,
          UIApplication.OpenURLOptionsKey.openInPlace : urlContext.options.openInPlace
        ]

        SCSDKLoginClient.application(
            UIApplication.shared,
            open: url,
            options: options)
    }

Disclaimer - I didn't test Snapchat code, just try to give you an idea.


text:
Q: how to change Postgres Table Field name limit? I want to create a table whose field name is of 100 characters but postgres limit for no of characters is 64 so how to change that limit to 100?
example:
Create table Test
(
PatientFirstnameLastNameSSNPolicyInsuraceTicketDetailEMRquestionEMR varchar(10)
)
This table creation fails as the name exceeds 64 characters

A: Actually name's limit is equal to NAMEDATALEN - 1 bytes (not necessarily characters), default value for NAMEDATALEN is 64.
NAMEDATALEN was determined at compile time (in src/include/pg_config_manual.h). You have to recompile PostgreSQL with new NAMEDATALEN limit to make it work.
However think about design and compatibility with other servers with standard 63 bytes limit. It's not common practice to use such long names.

A: It's because of the special name type (see table 8.5), which is used in pg_catalog. It won't accept anything longer than 63 bytes (plus terminator). There is no workaround.


text:
Q: Execute PHP script on FTP server connected to in another local PHP script is it possible to execute a php script on the server when connecting it. (not on the server, which builds the connection)?
<?php
// set up basic connection
$ftp_server = "localhost";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

$buff = ftp_rawlist($conn_id, '../ftpdest/index.php?action=download_now');
var_dump($buff);
ftp_close($conn_id);

A: Some, but not many, FTP servers support SITE EXEC command that allows you to execute arbitrary or selected shell commands on the server. The command can be remote php binary.
In PHP, you can use ftp_site function for that:
ftp_site($conn_id, "EXEC php -r \"echo 'Hello world!';\"");

But this will probably not work with your server. In most cases, you won't be able to execute a shell command over FTP.

If your FTP server is actually a web server, you can use FTP to upload a PHP script and then use the web server to execute the script.
ftp_put($conn_id, "/httpdocs/script.php", "/local/path/script.php");
file_get_contents("https://example.com/script.php");

If you have an SSH/shell access, use the SSH to execute your PHP script/code. The SSH is an API designed for executing script/code (contrary to FTP).


text:
Q: Calculadora em JavaScript + HTML Tenho que fazer uma calculadora em JavaScript para a aula, e estou a deparar-me com vários erros. Eu queria fazer em que primeiro escreve-se o número 1 e sem seguida escolher qual operação fazer, depois da operação escolhida introduzir o segundo número, e no fim clicar no botão "Enviar" que irá mostrar o resultado num alert, mas estou a ver dificuldade para fazer o mesmo. Poderiam ajudar-me?

      <title>Aula</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

   <form id="frm"  >

Aula de Web

               Nome:
               <input type="text" name="txtnome" placeholder="Introduza o seu nome">
               <input id="enviar" type="button" value="Enviar" onClick="ola('Ola')">

               Introduza os numeros:

               <input type="text" size="2" name="n1" placeholder="n1">

               <input type="text" size="2"  name="n2" placeholder="n2">

               <input type="button" value="+" onClick="soma()">
               <input type="button" value="-" onClick="subtracao('')">
               <input type="button" value="*" onClick="multiplicacao('')">
               <input type="button" value="/" onClick="divisao('')">

               <input type="button" value="Limpar" onClick="limpar()"/>
               <input type="button" value="Enviar" onClick="ola('Ola')">

   </form>

A:

function writeNumber(elementId) {
  var outputValueTo = document.getElementById('field1');

  if (outputValueTo.value == '0' || outputValueTo.value == 'Syntax error') {
    outputValueTo.value = elementId.textContent;
  } else {

    outputValueTo.value += elementId.textContent;
  }
}

function cleartxt() {
  document.getElementById('field1').value = '0';
  document.getElementById('dec').disabled = false;
}

function setOperator(elementId) {
  var outputValueTo = document.getElementById('field1');
  if (outputValueTo.value == '0' || outputValueTo.value == 'Syntax error') {
    outputValueTo.value = '0';
  } else {
    outputValueTo.value += elementId.textContent;
    document.getElementById('dec').disabled = false;
  }
}

function setDecimal(elementId, status) {
  var outputValueTo = document.getElementById('field1');
  outputValueTo.value += elementId.textContent;
  document.getElementById('dec').disabled = status;
}

function calculate() {

  try {

    var field1txt = document.getElementById('field1');
    if (field1txt.value != '') {
      var calculateResult = eval(field1txt.value);
      field1txt.value = calculateResult;
    }
  } catch (err) {

    field1txt.value = 'Syntax error';

  }

}

function removeLastNumber() {

  var field1txt = document.getElementById('field1');

  if (field1txt.value.length == 1 || field1txt.value == '0' || field1txt.value == 'Syntax error') {
    field1txt.value = '0';
    document.getElementById('dec').disabled = false;
  } else {
    field1txt.value = field1txt.value.substring(0, field1txt.value.length - 1);
  }
}
body {
  font-family: Verdana, sans-serif;
  font-size: 0.8em;
  margin: 0px;
  background: black;
}

nav,
section,
article {
  margin: 5px;
  padding: 8px;
}

#content {
  text-align: center;
}

header,
footer {
  background-color: Red;
  color: green;
  padding: 5px;
  margin: 0;
}

h1 {
  text-align: center;
}

button {
  width: 60px;
  text-align: center;
  font-size: 35px;
  background-color: red;
  color: black;
  border: cornflowerblue solid 1px;
  box-shadow: 1px 2px 3px 1px green;
  text-shadow: 1px 1px 3px green;
}

input {
  width: 250px;
  font-size: 30px;
  background-color: red;
  color: black;
  border: cornflowerblue solid 1px;
  text-align: right;
  box-shadow: 1px 2px 3px 1px green;
  text-shadow: 1px 1px 3px blue;
}

nav ul {
  margin: 0;
  padding: 0;
}

nav ul li {
  display: inline;
  margin: 5px;
}

        <input type='text' id='field1' readonly value='0' />

        <button onclick='writeNumber(this)' id='n1'>1</button>
        <button onclick='writeNumber(this)' id='n2'>2</button>
        <button onclick='writeNumber(this)' id='n3'>3</button>
        <button onclick='writeNumber(this)' id='n4'>4</button>

        <button onclick='writeNumber(this)' id='n5'>5</button>
        <button onclick='writeNumber(this)' id='n6'>6</button>
        <button onclick='writeNumber(this)' id='n7'>7</button>
        <button onclick='writeNumber(this)' id='n8'>8</button>

        <button onclick='writeNumber(this)' id='n9'>9</button>
        <button onclick='writeNumber(this)' id='n0'>0</button>
        <button onclick='setDecimal(this,true)' id='dec'>.</button>
        <button onclick='setOperator(this)' id='sum'>+</button>

        <button onclick='setOperator(this)' id='sustract'>-</button>
        <button onclick='setOperator(this)' id='multi'>*</button>
        <button onclick='setOperator(this)' id='divide'>/</button>
        <button onclick='cleartxt()' id='C'>C</button>

        <button onclick='calculate()' id='calcular' style='width:190px'>=</button>
        <button onclick='removeLastNumber()' id='removeLast'>B</button>

A: Como sua calculadora já está montada e não está funcional, vou sugerir estas alterações para fazê-la funcionar e simplificar seu código.
1. Crie apenas 1 função para fazer os cálculos, sem ter que fazer 1 função para cada operação matemática:
function calc(e){

   var operacao = e.value;

   var n1=parseFloat(document.getElementById("n1").value);
   var n2=parseFloat(document.getElementById("n2").value);

   var calculo = eval(n1+operacao+n2);

   if(!isNaN(calculo)){
      alert(calculo);
   }

}

2. Adicione onclick em cada botão de operação matemática chamando a função acima:
<input type="button" value="+" onclick="calc(this)">
<input type="button" value="-" onclick="calc(this)">
<input type="button" value="*" onclick="calc(this)">
<input type="button" value="/" onclick="calc(this)">

No final, seu código seria este:

function calc(e){

   var operacao = e.value;

   var n1=parseFloat(document.getElementById("n1").value);
   var n2=parseFloat(document.getElementById("n2").value);

   var calculo = eval(n1+operacao+n2);

   if(!isNaN(calculo)){
      alert(calculo);
   }

}

function ola(x){
   var f=document.getElementById("frm");
   var txt = f.txtnome;
   txt.value = "Ola "+txt.value;
}

function limpar(){
   //alert("1");
   var f=document.getElementById("frm");
   var n1 = f.n1;
   var n2 = f.n2;
   n1.value = "";
   n2.value = "";
}
<form id="frm"  >

Aula de Web

            Nome:
            <input type="text" name="txtnome" placeholder="Introduza o seu nome">
            <input id="enviar" type="button" value="Enviar" onClick="ola('Ola')">

            Introduza os numeros:

            <input type="text" size="2" id="n1" placeholder="n1">

            <input type="text" size="2"  id="n2" placeholder="n2">

            <input type="button" value="+" onClick="calc(this)">
            <input type="button" value="-" onClick="calc(this)">
            <input type="button" value="*" onClick="calc(this)">
            <input type="button" value="/" onClick="calc(this)">

            <input type="button" value="Limpar" onClick="limpar()"/>
            <input type="button" value="Enviar" onClick="ola('Ola')">

</form>


text:
Q: Reat native - How to fetch the CSV data from a link?
*

*The below Java code will extract the historical stock data from yahoo finance, but the output file is a CSV file that is being read and printed on the screen line by line.

*But I want to do the same thing in React native.

*It would be helpful if you guys can help me with the code for the same in react native.
 String link="https://query1.finance.yahoo.com/v7/finance/download/TSLA?period1=1563992913&period2=1595615313&interval=1d&events=history";

 URL url = new URL(link);
 URLConnection urlConn = url.openConnection();
 InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
 BufferedReader buf = new BufferedReader(inStream);

 String line =buf.readLine();
 while(line != null) {
     System.out.println(line);
     line=buf.readLine();
 }

This is the data inside the link  :
Date,Open,High,Low,Close,Adj Close,Volume
2019-07-24,259.170013,266.070007,258.160004,264.880005,264.880005,11072800
2019-07-25,233.500000,234.500000,225.550003,228.820007,228.820007,22418300
2019-07-26,226.919998,230.259995,222.250000,228.039993,228.039993,10027700
2019-07-29,227.089996,235.940002,226.029999,235.770004,235.770004,9273300

A: You could use a library such as Papa parse to do exactly this. It will also parse the data for you.
If we take the example from here, you could do something like this (assuming you would also like to print the data to the console):
import Papa from "papaparse"

const link = "https://query1.finance.yahoo.com/v7/finance/download/TSLA?period1=1563992913&period2=1595615313&interval=1d&events=history"

Papa.parse(link, {
    download: true,
    complete: results => console.log(results),
})


text:
Q: Angular: Behavioral Subject's value object is not extensible I'm trying to find the best way to update a value of a Behavioral Subject.
When I try to set an object's attribute value, I'm getting TypeError: Cannot add property sport, object is not extensible.
  selectSport(sport: Sport){
    this.match$.getValue().sport = sport;
  }

What is the best way to update Subject's data ?

A: The following is an example how it should be implemented:
selectSport(sport: Sport) {
  this.match$.next({ ...this.match$.getValue(), sport });
}


text:
Q: Need help to find total of specific name in column! (R-Coding) so I'm trying to find the total amount of each class in the Genus column, the following dataframe is shown below:
Genus/Species Dataframe
But it returns values of how many times each Genus is repeating, not it's total amount of the species observed.
I want a dataframe that looks like this:
Genus - Arachnida
Total Sum - (Total amount of Arachnida)
Thank you for whoever replies! (This is my first post, English is my second language so hopefully someone understands!)
I've tried using dplyr's function of count like:
BIO205 %>% count(Genus)
But it returns values of how many times each Genus is repeating, not it's total.
Like if I did BIO205 %>% count(Genus), it would return with
Returning Dataframe
This is indicating that the word Arachnida is repeating 21 times.

A: So it seems like you are trying to sum all the total values for each genus. If so group_by() is what you want. Here is a reprex:
library(dplyr)

data("iris")

iris %>%
    group_by(Species) %>%
    summarise(sum_col = sum(Sepal.Length))

The above code is grouping the data by species, followed by summing all the sepal lengths for each species. In your case, what I would try is the following code:
library(dplyr)

BIO205 %>%
    group_by(Genus) %>%
    summarise(sum_col = sum(Total))

Hope this helps.


text:
Q: I am getting this operational error while making my web app I am currently learning Python from a course Python by code with Mosh. In his course he has explained to build a web app using Django. While I was running my app on web server, I got an error "OPERATIONALERROR" and now I am stuck in it.
A picture of error I am receiving:

A: This is a Django bug.
Related question on Stack Overflow.
The solution as can be seen from the link is:
pip install Django --upgrade

Then:
python manage.py migrate

python manage.py makemigrations app

python manage.py migrate


text:
Q: Forking is transitive to the left I am trying to show that forking is transitive to
the left. i.e if $b\overset{\vert}{\smile}_{A}c
 $ and $a\overset{\vert}{\smile}_{Ab}c
 $ than $ab\overset{\vert}{\smile}_{A}c
 $

Edit: So I think I may got it but not so sure about it: If $p(x,y)=tp(ab/Ac)$ forks over $A$, than there is a forking formula $\varphi (x,y,c)\in p$ i.e $\varphi(x,y,c)$ implies a finite disjunction of formulas over $A$, $$\bigvee _i\varphi _i (x,y,c_i)$$ s.t $\varphi _i (x,y,c_i)$ divides over $A$. So there exist a $A$-indiscernible sequences $I_i=(d_j)_{j<\omega}$ s.t $I_i$ starts with $c_i$ and $$\pi(x,y,I_i)=\{\varphi _i (x,y,d_j)\mid j<\omega\}$$ is inconsistent. But  then $\pi(x,b,I_i)$ is also inconsistent, and since $\varphi (x,y,c)\in tp(ab/Ac)$ than $\varphi (x,b,c)\in tp(a/Abc)$ and $\varphi (x,b,c)$ implies $\bigvee _i\varphi _i (x,b,c_i)$. But we know that $\pi(x,b,I_i)$ is inconsistent, therefor $\varphi _i (x,b,c_i)$ divides over $A$. Hence $\varphi (x,b,c)$ forks over $A$. But we want it to fork over $Ab$ so we need to make an adjustment to $I_i$. There is an equivalence for dividing that say's $tp(a/Ab)$ does not divide over $A$ iff for any $A$-indiscernible sequence, there is a $Aa$-indiscernible sequence $I'$ s.t $I'\equiv_{Ab}I$. So since   $b\overset{\vert}{\smile}_{A}c
 $, than in particular $tp(b/Ac)$ does not divide over $A$, Hence for every $i$ there is a $Ab$-indiscernible sequence $J_i$ s.t $J_i \equiv_{Ac} I_i$ and with the right automorphism we can make sure that $J_i$ starts with $c_i$. Thus $\pi(x,b,J_i)$ is inconsistent and therefor  $\varphi _i (x,b,c_i)$ divides over $Ab$ and so $\varphi (x,b,c)$ forks over $Ab$ in contradiction to $a\overset{\vert}{\smile}_{Ab}c
 $. And we are done.
is it right?


text:
Q: How can I extract the columns of data with Perl? I have strings of this kind
NAME1              NAME2          DEPTNAME           POSITION
JONH MILLER        ROBERT JIM     CS                 ASST GENERAL MANAGER

I want the output to be name1 name2  and position how can i do it using split/regex/trim/etc and without using CPAN modules?

A: It's going to depend on whether those are fixed length fields, or if they are tab separated.  The easiest (using split) is if they are tab separated.
my ($name1, $name2, $deptName, $position) = split("\t", $string);

If they're fixed length, and assuming they are all, say, 10 characters long, you can parse it like
my ($name1, $name2, $deptName, $position) = unpack("A10 A10 A10 A10", $string);

A: If your input data comes in as an array of strings (@strings), this
for my $s (@strings) {
   my $output = join ' ',
                map /^\s*(.+)\s*$/ ? $1 : (),
                unpack('A19 A15 x19 A*', $s);
   print "$output\n"
}

would extract and trim the information needed.

NAME1 | NAME2 | POSITION

and

JONH MILLER | ROBERT JIM | ASST GENERAL MANAGER

(The '|' were included by me for better expalnation of the result)
Regards
rbo

A: Assuming that space between the fields are not fixed so split string on the basis of two or more spaces so that it will not break the Name like JONH MILLER into two parts.
#!/usr/bin/perl
use strict;
use warning;
my $string = "NAME1              NAME2          DEPTNAME           POSITION
             JONH MILLER        ROBERT JIM     CS                 ASST GENERAL MANAGER ";
my @string_parts = split /\s\s+/, $string;
foreach my $test (@string_parts){
      print"$test\n";
}

A: From the sample there, a single space belongs in the data, but 2 or more contiguous spaces do not. So you can easily split on 2 or more spaces. The only thing I add to this is the use of List::MoreUtils::mesh
use List::MoreUtils qw<mesh>;
my @names   = map { chomp; $_ } split /\s{2,}/, <$file>;
my @records = map { chomp; { mesh( @names, @{[ split /\s{2,}/ ]} ) } } <$file>;

A: To split on whitespace:
@string_parts = split /\s{2,}/, $string;

This will split $string into a list of substrings.  The separator will be the regex \s+, which means one or more whitespace characters. This includes spaces, tabs, and (unless I'm mistaken) newlines.
Edit: I see that one of the requirements is not to split on only one space, but to split on two or more.  I modified the regex accordingly.

A: Consider using autosplit in a Perl one-liner from your command line:
$ perl -F/\s{2,}/ -ane 'print qq/@F[0,1,3]\n/' file

The one-liner will split on two or more consecutive spaces and print the first, second and fourth fields, corresponding to NAME1, NAME2 and POSITION fields.
Of course, this will break if you have only a single space separating NAME1 and NAME2 entries, but more information is needed about your file in order to ascertain what the best course of action might be.


text:
Q: How to use 'children' jQuery selector to only show content of a child span of a div? I have the html like this"

        took

I want to get the took
so how can i use the children jquery  for this ?
I have tried:

A: For valid html ids are unique so you can use only row1, One more thing put the code in document.ready to ensure availability to javascript/jquery.
Live Demo
$(document).ready(function(){
  $('#row1').children('.highlight').each(function(){
      alert($(this).text());
  });
});

You even do not need each if you get only one element by selector.
 var forTook = $('#row1').children('.highlight').text();

or
var forTook = $('#row1 .highlight').text();

A: Just to elaborate; you can't alert a jquery object like in your example:
var a = $("#words").children('#row1').children('.highlight');

In this case, a would be a jQuery object, which has an array-like structure.
With the above in mind (assuming that you have selected the right elements) you can iterate over it like in @Adil's example:
$.each(a, function(i, el){
    alert($(el).text());
});

A: Try this: use .find() with .children()
$("#words").children().find('.highlight').text();

A: If you have multiple .highlight elements in your HTML, you will have to iterate over them:
$('#row1 .highlight').map(function() {
    return $(this).text();
}).get();

This will return an array containing all of the highlighted words.

A: You were almost there:

As Adil has said, you'll need to loop over the matching elements if there are more than one.


text:
Q: Как в макрос вставить функцию из определенного пространства имен? хочу вот так.
#define FUNCTION ( name, action ) namespace1::##name::foo( action )

ошибка звучит так
src/ .cpp:69:25: error: 'name' was not declared in this scope
#define FUNCTION ( name, action ) namespace1::##name::foo( action )
минимальный пример (рабочий):
namespace cotrol
{
namespace namespace1
{
    void foo( int x ) {}
} // namespace namespace1

namespace namespace2
{
    void foo( int x ) {}
} // namespace namespace2

} // namespace control

#define ACTION( name, action ) cotrol::name::foo( action )

int main()
{
    ACTION ( namespace1, 5 );
    ACTION ( namespace2, 10 )

    return 0;
}


text:
Q: MongoDB Regex $and $or Search Query I am trying to construct a query that will accept multiple fields that can be searched over using regex for partial field matching that also has a hard constraint on other fields.
Example:
Collection: "Projects"
Required Information: { propertyId: "abc", clientId: "xyz" }
Fields to be Searched: name, serviceType.name, manager.name
Currently, I have a query like this, but if there are no results it returns all the results, which isn't helpful.
{
 '$and': [
    { propertyId: '7sHGCHT4ns6z9j6BC' },
    { clientId: 'xyz' },
    { '$or':
     [
       { name: /HVAC/gi },
       { 'serviceType.name': /HVAC/gi },
       { 'manager.name': /HVAC/gi }
     ]
    }
 ]
}

If anyone has any insight into this it would be much appreciated.
Example Document:
{
  _id: "abc",
  propertyId: "7sHGCHT4ns6z9j6BC",
  clientId: "xyz"
  name: "16.000.001",
  serviceType: {
    _id: "asdf",
    name: "HVAC"
  },
  manager: {
    _id: "dfgh",
    name: "Patrick Lewis",
  }
}

The expected result is to only find documents where propertyId = 7sHGCHT4ns6z9j6BC AND one at least one of the following keys: name, serviceType.name, or manager.name match an inputted string, in this case, it's HVAC and if none of the regex fields match, then return nothing.
UPDATE
The issue was with MongoDB, after restarting it, everything worked.

A: Try following script:
db.collection.find({
$and:[
  {propertyId:"7sHGCHT4ns6z9j6BC"},
  {
    $or:[
       {name: /HVAC/i},
       {"serviceType.name": /HVAC/i},
       {"manager.name": /HVAC/i}
    ]
  }]
})

Query above will return a document or documents if and only if propertyId matches and either of name, serviceType.name or manager.name matches desired regex.


text:
Q: How to properly handle locale change at runtime with Android 24+ multi window mode? Just out of curiosity: how should I handle locale change in the phone's setting menu if user use the multi window mode to open my app and the settings side by side? How can I notify all the string resources and stuff change accordingly, and how to I trigger some logic to run (e.g. API call requires locale so I have to re-fetch everything)? Right now I am using a broadcast receiver that triggers System.exit(0); to launch the whole app again. But obviously this does not translate well into multi window mode.
Thanks!

A: A locale change is a configuration change, just like orientation. If you want to handle it manually, you can have your activity handle it using android:configChanges="locale" attribute. You can get the locale from the Configuration in onConfigurationChanged() using getLocales().get(0), compare it with current locale and handle the change when detected.
Else, I expect your activity to be recreated and you can handle the locale for a new activity in a single uniform fashion.


text:
Q: How does correct gamma color on external screen? Linux laptop I have got a laptop and i would like to correct gamma color on my external screen.
My system: Laptop, VGA port, Linux, Ubuntu.
In option System->Preferences->Monitor i turn off my laptop's screen.
But bash-command  xgamma -gamma 5 does not any effect. BTW on laptop is (if it will turn on) too.
How can i get it?

A: You can use the xrandr utility to change the gamma settings on external displays.
Here is how it works:
xrandr --output VGA-0 --gamma 1.5:1.5:1.5

Replace 1.5 with other values and see what works for you.
Also, to get the correct identifier for your external display (VGA-0 in my case) you can run
xrandr -q

to get a listing of all displays recognized in your system.


text:
Q: Best Java deobfuscation tools as of date - [ques Closed] we have obfuscated our java source code and currently working on it, so make our source fool proof what are all thing to be done while obfuscation ?, how it can be prevented from de-obfuscation? and
What are all the de-obfuscation open source tool available right now?

A: There is no such thing as a deobfuscation tool.  What you are actually talking about is a decompiler.
A good obfuscator will remove most of the clues that a decompiler needs to produce readable source code.  However, it will not prevent someone with enough skill and determination from reverse engineering your code anyway.  In fact, there is NOTHING you can do to prevent that.
If you want to make a judgement on how easy / hard it would be, then the best answer is to attempt to do the reverse engineering yourself ... using all of the decompilers you can get your hands on.  (I imagine that you are really worried about someone attacking a critical part ... like the license key checking.  So focus on reverse engineering / circumventing that.)

A: For Java I have used this obfuscation tool in the past with success: http://proguard.sourceforge.net/#
As a bonus it also shrinks the code.
I've never tried obfuscating my c/c++ code. This is the one of the obfuscators I know for c/c++ though I have never used it: http://freecode.com/projects/cxx-obfus

A: We use Proguard in our company.


text:
Q: Check select Change After Ajax Call Hy everyone I searched a lot for a solution but I don't find any suggestion, thanks for your help ;)
My problem is that I have 2 or 3 selects within a form like that:

<select name="type" id="type">
  <?php for($i=0;$i<sizeof($id);$i++){?>
        <option value="<?php echo $id[$i] ?>"><?php echo $nom[$i] ?></option>
  <?php } ?>
</select>

  <select name='largeur' id='largeur'>
    <?php for($i=0;$i<sizeof($largeur);$i++){ ?>
     <option value='<?php echo $largeur[$i] ?>'><?php echo $largeur[$i] ?></option>
    <?php } ?>
  </select>

  <select name='hauteur' id='hauteur'>
    <?php for($i=0;$i<sizeof($hauteur);$i++){ ?>
     <option value='<?php echo $hauteur[$i] ?>'><?php echo $hauteur[$i] ?></option>
    <?php }?>
  </select>

SO I want to change #largeur value relatively to #type and #hauteur value relatively to #type with ajax, my ajax is:

$(document).ready(function(){
  $("#type").on('change',function(){
  var type = $('#type').val();
    $.ajax({
      url: 'check.php',
      type: 'POST',
      data: {type:type,act:'type'},
      success:function(data){
        $('#largeurHolder').show();
        $('#largeurHolder').html(data);
      }

    });
    $('#hauteurHolder').html('<select disabled="disabled"></select>');
 return false;
  });

  $("#largeur").on('change',function(){
 alert('koko');
    var type = $('#type').val();
 var largeur = $('#largeur').val();
 $('#hauteurHolder').hide();
 $.ajax({
   url: 'check.php',
  type: 'POST',
  data: {type:type,largeur:largeur,act:'largeur'},
    success:function(data){
   $('#hauteurHolder').show();
   $('#hauteurHolder').html(data);
    }
 });

  });
 return false;
});

About the script check.php it return values like that:

<?php
if($_POST['act']=='type'): //------------TYPE ACTION
  list($largeur) = GetALlLargeursFromPneus($db,$_POST['type']);
  echo '<select name="largeur" id="largeur">';
  echo '<option value="">Choisissez</option>';
  for($i=0;$i<sizeof($largeur);$i++)
  {
    echo '<option value="'.$largeur[$i].'">'.$largeur[$i].'</option>';
  }
  echo '</select>';

  elseif($_POST['act']=='largeur'): //------------LARGEUR ACTION
    list($hauteur) = GetALlHauteursFromPneus($db,$_POST['type'],$_POST['largeur']);
    echo '<select name="hauteur" id="hauteur">';
 echo '<option value="">Choisissez</option>';
 for($i=0;$i<sizeof($hauteur);$i++)
 {
   echo '<option value="'.$hauteur[$i].'">'.$hauteur[$i].'</option>';
    }
   echo '</select>';
  endif;
?>

The problem is that when I change #type all works fine but when I would to change #largeur after Ajax call it don't work.
Note that when I change #largeur without changing #type is work fine, So i think that my problem is after ajax call.
Thank you in advance.


text:
Q: How to get an entry point address in binary image file generated by objcopy? I am building an emulator of the Risk-V CPU for own educational purposes. I have small POC working and want to build example programs and test them on the emulator.
I'm trying to build example program in Rust and seems like I made some decent progress, but I got stuck when I have to load compiled program to the memory of my emulator and transfer CPU execution to that program.
Test program:
#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[no_mangle]
pub extern "C" fn _start() -> ! {
    loop {
        for i in 0..1000 {
            unsafe {
                let r = i as *mut u32;
                // This can panic because (500 - i) can be 0
                *r = 20000 % (500 - i);
            }
        }
    }
}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

build:
$ cargo build --target riscv32i-unknown-none-elf --release

generating binary image from elf target:
riscv32-unknown-linux-gnu-objcopy -g -O binary \
  target/riscv32i-unknown-none-elf/release/sample1 \
  target/riscv32i-unknown-none-elf/release/sample1.bin

This works fine so far and generates me binary file with size 5156 bytes.
I inspected .bin file and it looks "legit binary" to me.
I found some readable strings in the beginning of the file (like attempt to calculate the remainder with a divisor of zero) - looks like they are related to code which handles panic which can happen if I'm doing % 0.
In the end of file I found something that looks like riskv32i instructions (easy to notice them since least significant bits are 11).
Rest of the file is filled with zeros.
Place where I stuck is I cannot figure out:

*

*At which offset am I supposed to load this bin image file into memory of my virtual CPU? I don't think it's OK to load it at 0x0 address, because there is useful info in the beginning of the image and I don't think it's cool for the program to read it from address 0x0.

*After program is loaded, I need to transfer CPU execution to the entry point of my program (_start). How can I find out which address is the entry point so I can put this address into pc register before starting CPU cycles? It's obviously not in the beginning of the image (there are human readable strings there).

*Is there a way to make this entry point address stable, so all programs which I write will have the same entry point address, so I don't have to do tweaks for each of programs I compile?

I may went wrong way when I used objcopy. If that's the case, please let me know what's the appropriate way to load ELF file into a homemade CPU emulator.
Update: Linker arguments, (as provided by RUSTFLAGS="-Z print-link-args" cargo build --target riscv32i-unknown-none-elf --release --verbose):
rust-lld \
    -flavor \
    gnu \
    -L \
    /home/kris/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/riscv32i-unknown-none-elf/lib \
    /mnt/c/src/ws/cpu/sample1/target/riscv32i-unknown-none-elf/release/deps/sample1-4813691a581d1819.sample1.251h7tq6-cgu.0.rcgu.o \
    /mnt/c/src/ws/cpu/sample1/target/riscv32i-unknown-none-elf/release/deps/sample1-4813691a581d1819.sample1.251h7tq6-cgu.1.rcgu.o -o \
    /mnt/c/src/ws/cpu/sample1/target/riscv32i-unknown-none-elf/release/deps/sample1-4813691a581d1819 \
    --gc-sections \
    -L \
    /mnt/c/src/ws/cpu/sample1/target/riscv32i-unknown-none-elf/release/deps \
    -L \
    /mnt/c/src/ws/cpu/sample1/target/release/deps \
    -L \
    /home/kris/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/riscv32i-unknown-none-elf/lib \
    -Bstatic \
    /home/kris/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/riscv32i-unknown-none-elf/lib/librustc_std_workspace_core-6d1cf467df9db3bb.rlib \
    /home/kris/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/riscv32i-unknown-none-elf/lib/libcore-a1a0b4993598bfe4.rlib \
    /home/kris/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/riscv32i-unknown-none-elf/lib/libcompiler_builtins-a229bbbccd019775.rlib \
    -Bdynamic

I know that there are some important things missing in the program, like initializing stack pointer register. I'm planning to take care about that after I figure out loading logic

A: Disclaimer: I am not familiar with Rust, but your question is more related to the ELF file format and tools that can understand it - my two cents.

*

*Which offset you should load your binary file at should probably be guided by the linker settings rust-ldd is using.

For example, this documentation describes a file memory.x defining the memory map used by the linker:
MEMORY
{
  RAM : ORIGIN = 0x80000000, LENGTH = 16K
  FLASH : ORIGIN = 0x20000000, LENGTH = 16M
}

REGION_ALIAS("REGION_TEXT", FLASH);
REGION_ALIAS("REGION_RODATA", FLASH);
REGION_ALIAS("REGION_DATA", RAM);
REGION_ALIAS("REGION_BSS", RAM);
REGION_ALIAS("REGION_HEAP", RAM);
REGION_ALIAS("REGION_STACK", RAM);

In this example, the resulting binary should probably be loaded at offset 0x20000000.
There should be an equivalent with the toolchain you are using.

*You can find _start using a tool that understands the ELF file format.

For example, aarch64-none-elf-nm on one of my executables compiled for Aarch64 will display:
aarch64-none-elf-nm h5-example.elf
0000000042000078 t $d
0000000042000000 t $x
0000000042000080 t $x
00000000420001dc t $x
00000000420001f4 t $x
0000000042000230 B __bss_end__
0000000042000230 B __bss_start__
0000000042000080 T c_entry
000000004200022c D __copy_table_end__
0000000042000220 D __copy_table_start__
0000000042000230 D __data_end__
0000000042000230 D __data_start__
0000000042000230 ? __end__
0000000042000230 B __etext
0000000042000218 T __exidx_end
0000000042000218 T __exidx_start
0000000042000230 d __fini_array_end
0000000042000230 d __fini_array_start
0000000046000230 ? __HeapLimit
0000000004000000 A __HEAP_SIZE
0000000042000230 d __init_array_end
0000000042000230 d __init_array_start
00000000420001f4 T main
0000000042000000 A __RAM_BASE
000000000e000000 A __RAM_SIZE
0000000042000000 T Reset_Handler
0000000000000000 A __ROM_BASE
0000000000000000 A __ROM_SIZE
000000004c000000 ? __StackLimit
0000000004000000 A __STACK_SIZE
0000000050000000 ? __StackTop
00000000420001dc t system_read_CurrentEL
0000000042000230 B __zero_table_end__
0000000042000230 B __zero_table_start__

In my case, the first instruction be be executed would be at Reset_Handler.
I could retrieve the line referencing it using the following command:
aarch64-none-elf-nm h5-example-02.elf | grep ' Reset_Handler$'
0000000042000000 T Reset_Handler

and its exact address in hexadecimal using:
aarch64-none-elf-nm h5-example-02.elf | grep ' Reset_Handler$' | cut -d ' ' -f1
0000000042000000

RESET_HANDLER=$(aarch64-none-elf-nm h5-example-02.elf | grep ' Reset_Handler$' | cut -d ' ' -f1)
echo ${RESET_HANDLER}

would of course display:
0000000042000000

Now the start address is known, there would be several options for using it in your DIY emulator. The two that came to my mind would be:
a) pass the address as an argument to your emulator, i.e.:
my-emulator 0000000042000000 or my-emulator -s 0000000042000000
b) since you master the format of the image your emulator will load, you could convene to systematically prepend the start address to the binary file produced by objcopy: this way, you would read the first 4 or 8 bytes of the binary file first, getting your start address, then read the remaining bytes.
An easy way to do so would for example  to use xxd and cat:
echo 0000000042000000 | xxd -r -p > final-image.bin
cat sample1.bin >> final-image.bin

Using an example file containing 'ABCD', we would get:
printf "ABCD" > sample1.bin
hexdump -C sample1.bin
00000000  41 42 43 44                                       |ABCD|
00000004

echo 0000000042000000 | xxd -r -p > final-image.bin
hexdump -C final-image.bin

00000000  00 00 00 00 42 00 00 00                           |....B...|
00000008

cat sample1.bin >> final-image.bin
hexdump -C final-image.bin
00000000  00 00 00 00 42 00 00 00  41 42 43 44              |....B...ABCD|
0000000c

You could of course define a more complicated header, may be containing some other important symbols, or add more command-line options to you emulator - the basic principle would remain the same.

*Yes, you could probably force your compiler to put the _start() function into a specific linker section, as described here, using the link_section directive/pragma:

Program:
#[no_mangle]
pub unsafe extern "C" fn Reset() -> ! {
    let _x = 42;

    // can't return so we go into an infinite loop here
    loop {}
}

// The reset vector, a pointer into the reset handler
#[link_section = ".vector_table.reset_vector"]
#[no_mangle]
pub static RESET_VECTOR: unsafe extern "C" fn() -> ! = Reset;

Linker script:
/* Memory layout of the LM3S6965 microcontroller */
/* 1K = 1 KiBi = 1024 bytes */
MEMORY
{
  FLASH : ORIGIN = 0x00000000, LENGTH = 256K
  RAM : ORIGIN = 0x20000000, LENGTH = 64K
}

/* The entry point is the reset handler */
ENTRY(Reset);

EXTERN(RESET_VECTOR);

SECTIONS
{
  .vector_table ORIGIN(FLASH) :
  {
    /* First entry: initial Stack Pointer value */
    LONG(ORIGIN(RAM) + LENGTH(RAM));

    /* Second entry: reset vector */
    KEEP(*(.vector_table.reset_vector));
  } > FLASH

  .text :
  {
    *(.text .text.*);
  } > FLASH

  /DISCARD/ :
  {
    *(.ARM.exidx .ARM.exidx.*);
  }
}

This way, the code for the _start() function would always be put at the beginning of the .vector_table section, which is defined a being the first in the FLASH region.
The address for _start() would therefore always be 0x00000000, or whatever address you will decide the reset address will be in your CPU: you would just have to modify the address where the FLASH region is starting from.
The example is related to an Arm Cortex-M MCU, and you could replace the .vector_table section by, say, your own .startup section.
I hope I was not off-track on that one...


text:
Q: Remove class('has-error') after entering valid answer in select2 using jquery validate I am using select2 for dropdown and jquery validate. After entering valid input, error class should be removed, and it is working with other inputs like texts, but select is retaining this class.
I tried doing so:
$.validator.setDefaults({
    errorClass: 'help-block',
    errorElement: 'span',
    focusInvalid: true,
    highlight: function(element, errorClass, validClass)
    {

      var fieldtype = ($(element).hasClass('dateField') ? 'dateField' : 'normal');
      switch(fieldtype)
      {
        case "dateField":
          $(element).closest('.form-group').addClass('has-error');
          // $(element).select();
          break;
        default:
          $(element).closest('.form-group').addClass('has-error');
          break;
      }

    },
    unhighlight: function(element, errorClass, validClass)
    {
      if($(element).hasClass('select2-offscreen'))
      {
        $(element).closest('.form-group').removeClass('has-error');
        $(element).next('span').css({display: "block"});
      }
      else
      {
        $(element).closest('.form-group').removeClass('has-error');
      }
    },

    errorPlacement: function (error, element) {
            var fieldtype = ($(element).hasClass('dateField') ? 'dateField' : 'normal');

            switch (fieldtype) {
                case "dateField":
                    if (window && window.console) {
                        console.log("Date type field type");
                    }
                    error.appendTo(element.parent().parent());
                    break;
                default:
                    if (window && window.console) {
                        console.log("Regular field type");
                    }
                    error.appendTo(element.parent());
                    break;
            }
        }
  });
  $('#employee-form').validate(
  {
    rules: {
            firstname: {
                alpha: true,
                required: true
            },
           },
messages: {.....
});

Here's my html:

  Designation *

    <select name="designation_id" class="form-control" id="designations">
     <option></option>
     <option value="<?php echo $designation->id; ?>"><?php echo $designation->title; ?></option>
     </select>

Here's select2 initialization:
$('#designations').select2({
    sortResults: function (results) {
        return results.sort();
    },
    placeholder: "Select designation",
    allowClear: true
});

I manually tried to remove errorClass and add style="display: none" to error element, but it doesn't work. Help me please.

A: I think the setTimeout should do the job here. Please change your validate plugin settings as given here:
unhighlight: function(element) {
    if (jQuery(element).is('#designations')) {
        setTimeout(function(){
            $(element).closest('.form-group').removeClass('has-error');
        },50);
    }
}

and add following code additionally:
jQuery("#designations").on('change', function (evt) {
    $thisVal = jQuery("#designations").val();
    if($thisVal != '') {
        setTimeout(function(){
            jQuery("#test-form").validate().element('#designations');
        },100);
    }
});

If you still have issues, kindly send the url and i will test it for you.


text:
Q: Cannot read property 'entries' of undefined in http://maps.googleapis.com/maps/api/ Everything worked and suddenly there was a mistake Cannot read property 'entries' of undefined that it could be ? (including googlemaps api)
Uncaught TypeError: Cannot read property 'entries' of undefined
    at js?key=<API_KEY>&callback=Map.init:105
Map.init
    Map.init = function (id) {
    id = id || 'map';
    map = new google.maps.Map(document.getElementById(id), {
        center: {lat: 46.409998, lng: 30.710000},
        scrollwheel: true,
        zoom: this.address ? 20 : 12
    });

    infoWindow = new google.maps.InfoWindow();

    map.addListener('zoom_changed', function () {
        var zoom = map.getZoom();
        if (zoom > zoomShowPoints && !pointsVisibility) {
            pointsVisibility = true;
            points.forEach(function (item) {
                item.setVisible(pointsVisibility);
            });
        } else if (zoom <= zoomShowPoints && pointsVisibility) {
            pointsVisibility = false;
            points.forEach(function (item) {
                item.setVisible(pointsVisibility);
            });
        }
    });

    getUsers();
};

A: Google changed their Maps API script November 2017.  They started using global variable Map which broke our site.  Renaming the Map variable to OurMap in our script fixed the issue.
var Map;

changes to;
var OurMap;

A: it was solved by adding version param
https://maps.googleapis.com/maps/api/js?v=3&key=&callback=Map.init


text:
Q: Renaming Column Values Efficiently I am trying to rename values in my data all at once, rather than doing it entry by entry.
Right now I am using this code to perform my changes:
INV$Classification[INV$Classification=="lay net"] <- "Illegal Lay Net"

My data is INV, and my column is Classification. I want to find all instances of the words "lay net" and replace them with "Illegal Lay Net". I am doing this manually right now, which I could ultimately do in excel. Is there a more efficient way to do this?
For Example I have entries such as: POSSIBLE ILLEGAL LAY NET or Lay Nets Violation, these do not get picked up by just using the "lay net" find and thus are not switched because this code is very specific.

A: You want to start using regular expressions.  Take a look at gsub, grep, grepl and similar functions.  Of course it is not a magic bullet, you still have to understand and make sure you catch every case.
Here is an example that will catch the 3 cases you said:
INV$Classification[grepl("lay net", INV$Classification, ignore.case=T)] <- "Illegal Lay Net"

A: Here's a verbose tidyverse solution using stringr, first converting to lowercase and then testing if that includes "lay net," replacing with the new string if it does.
library(tidyverse)
INV <- INV %>%
  mutate(Classification = if_else(Classification %>%
                                  tolower %>%
                                  str_detect("lay net"),
                                  "Illegal Lay Net", Classification)


text:
Q: How do I compile and install a Cydia app? I have downloaded iSwipe from Cydia and I really like it, but it lacks a dictionary of italian words. I have found the original github repository of iSwipe and it gives access to the code.
I would like to modify it to allow for the use of multiple languages, but I have never programmed any iPhone apps nor I know how to compile them and run them as Cydia apps.
Apart from forking the repository and modifying the code to my fit my needs, which I know how to do, could anybody kindly guide me through the process of compiling it and installing it on my phone to test it?
I am using Windows and don't have access to an OS X workstation, is it still possible?
P.S.: if this is the wrong site for this question, please move it. Thanks.

A: Install iFile for your iPhone/iPod/iPad/whatever(the free version will do) and navigate to /var/mobile/Wynd/Swype . There you can find the dictionary and you can edit however you want.
Now I have a question for you, where will you find the complete dictionary of words? :)


text:
Q: Month and year picker in ionic framework I am looking for a month and year picker for my ionic app. currently I am using http://ngcordova.com/docs/plugins/datePicker/
But I dont want the day picker in here . How to have only month and year to pick?
I am trying to get something like

A: you can refer to this component.........
https://github.com/petruisfan/ionic-monthpicker

A: This is the answer to the following question.
<ion-datetime displayFormat="MM/YYYY" min="1994-03-14" max="2012-12-09"></ion-datetime>

displayFormat="MM/YYYY" you can use this for formating the Callander.


text:
Q: saving the features of an object in an excel file to be trained with svm using Accord.Net I took a look on Surf and SVMs samples in accord library samples.I wonder how can I save the features I get from "SURF" in the excel file, because the feature ( i.e. interest point ) is a record contains some fields and a array of float (Descriptor) and in the SVMs sample all the columns are just a value, no record contains a list, for example in the XOR classification the input (one feature) is
(x =0 , y=0 , G=1)
but here I have a record that contains the next fields :
( Laplacian  : int ,    Orientation  : float    , Response  : float     ,Scale : float ,    X  :  float , Y   : float  , Descriptor   : [] float   )

and I'm not sure but if I want to make like the XOR problem I should add a field of the object name . I found that the SVM takes a matrix, I can't figure out how can I make this compatibility between these two samples, I hope my question is clear.
Thanks in advance

A: The question is a bit unclear, but I will propose a solution. As a disclaimer, and to avoid further complications, I should say I am the author of this library.
If all you want is to train a SVM using SURF features, then you could skip the Excel part. It should be more useful to create a bag-of-visual-words representation of your images, and then store this representation instead of the SURF features.
It seems this question was asked before the image classification sample application was released, so please take a look on it if you are still interested in the answer.
In any case, the bag-of-visual-words model is able to transform your variable-length number of features into fixed length vectors, which should be easier manage, either if you would like to train SVMs or just store then in a file. Here is an example on how to use the BoW model to extract fixed-length features:
// Create bag-of-words (BoW) with the given number of words
BagOfVisualWords bow = new BagOfVisualWords(numberOfWords);

bow.Compute( ... ); // pass all images in the training set

// And then you can create a fixed-length
// representation of an given image using
double[] featureVector = bow.GetFeatureVector(image);

I will refrain from posting any links here so it doesn't looks like I am promoting my own project even further, but the classification sample application is available both under your start menu, if you have installed using the executable installer; and in the project's website.


text:
Q: Map Firestore DocumentSnapshot to Properties In a Class I have code like this for QuerySnapshot to get documents in collection that works good.
List<DaftarHazard> _userHazardFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.documents.map((hazards) {
      return DaftarHazard(
          waktuHazard: hazards.data['waktuHazard'],
          judulHazard: hazards.data['judulHazard'],
          isiHazard: hazards.data['isiHazard'],
          fotoHazard: hazards.data['fotoHazard'],
          namaPelapor: hazards.data['namaPelapor'],
          lokasiHazard: hazards.data['lokasiHazard'],
          statusHazard: hazards.data['statusHazard']);
    }).toList();
  }

  Stream<List<DaftarHazard>> get userHazardAsSuper {
    return userHazards.snapshots().map(_userHazardFromSnapshot);

  }

But then I need to Map DocumentSnapshot to class properties.
I don't know how to get this done.
How can I do this using the same method that I use for the QuerySnapshot?
The code above I get from collections.
Code below is the one I use to get fields in a document
Stream<List<UserDetails>> get userDetails {
    return userData.document(uid).snapshots().map(_userDetailsFromSnapshot);
  }

and using this to map to the properties
List<UserDetails> _userDetailsFromSnapshot(DocumentSnapshot snapshot) {
    return snapshot.data.map((item) {
      return UserDetails(
        name: details.['name'],
        email: details.data['email'],
      );
    }).toList();
  }

But code above does not work.
Found the solutions here:
Net Ninja

A: You to extract the data from your DocumentSnapshot.
List<DaftarHazard> _userHazardFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.documents.map((hazards) {
       return DaftarHazard(
          waktuHazard: hazards.data['waktuHazard'] != null ?  WaktuHazard.fromData(hazards.data['waktuHazard'].data) : null,
          judulHazard: hazards.data['judulHazard'],
          isiHazard: hazards.data['isiHazard'],
          fotoHazard: hazards.data['fotoHazard'],
          namaPelapor: hazards.data['namaPelapor'],
          lokasiHazard: hazards.data['lokasiHazard'],
          statusHazard: hazards.data['statusHazard']);
    }).toList();
  }

And replace each property for its own object instead of DocumentSnapshots.
I'm not sure of the structure that you want, but basically, you just need to access the data property of your DocumentSnapshot and parse it accordingly.

A: Found the solution for getting field and value from a specific document in firestore here
[Net Ninja][1]


text:
Q: Save the exif metadata using the new PHPhotoLibrary I am currently using AVCaptureStillImageOutput to get a full resolution picture. I am also able to get the exif metadata using the following code:
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {

         CFDictionaryRef metaDict = CMCopyDictionaryOfAttachments(NULL, imageSampleBuffer, kCMAttachmentMode_ShouldPropagate);
         CFMutableDictionaryRef mutableDict = CFDictionaryCreateMutableCopy(NULL, 0, metaDict);

         NSLog(@"test attachments %@", mutableDict);

         // set the dictionary back to the buffer
         CMSetAttachments(imageSampleBuffer, mutableDict, kCMAttachmentMode_ShouldPropagate);

         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];

         UIImage *image = [[UIImage alloc] initWithData:imageData];
         [self.delegate frameReadyToSave:image withExifAttachments: mutableDict];
     }];

The metadata being located in the mutableDict variable. Now, I want to save this picture in two different places, with the metadata. I want to save it on the disk in the application folders and in the Photo Library.
Now, I tried to save the image, in another method, using the following (the image variable you see is a custom object):
NSData* imageData = UIImageJPEGRepresentation(image.image, 1.0f);

[imageData writeToFile:image.filePath atomically:YES];

UIImageWriteToSavedPhotosAlbum(image.image, nil, nil, nil);

Now, the image is properly saved but does not contain any Exif metadata.
From what I have read, I need to use the PHPhotoLibrary to do so but the documentation isn't too loquacious on that. Here's what I found:
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image.image];

} completionHandler:nil];

But how do I save the metadata with it?

A: I would suggest you use ImageIO to accomplish that:
-(void)frameReadyToSave:(UIImage*)image withExifAttachments:(NSMutableDictionary*)mutableDict
{
    NSData* imageData = UIImageJPEGRepresentation(image, 1.0f);
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef) imageData, NULL);
    __block NSURL* tmpURL = [NSURL fileURLWithPath:@"example.jpg"]; //modify to your needs
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef) tmpURL, kUTTypeJPEG, 1, NULL);
    CGImageDestinationAddImageFromSource(destination, source, 0, (__bridge CFDictionaryRef) mutableDict);
    CGImageDestinationFinalize(destination);
    CFRelease(source);
    CFRelease(destination);
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:tmpURL];
    }   completionHandler:^(BOOL success, NSError *error) {
        //cleanup the tmp file after import, if needed
    }];
}

A: Use this to merge metadata into image data and save it to Photo Library:
func saveImageData(data: Data, metadata: NSDictionary? = nil, album: PHAssetCollection, completion:((PHAsset?)->())? = nil) {
    var placeholder: PHObjectPlaceholder?

    PHPhotoLibrary.shared().performChanges({
        var changeRequest: PHAssetChangeRequest

        if let metadata = metadata {
            let newImageData = UIImage.mergeImageData(imageData: data, with: metadata)
            changeRequest = PHAssetCreationRequest.forAsset()
            (changeRequest as! PHAssetCreationRequest).addResource(with: .photo, data: newImageData as Data, options: nil)
        }
        else {
            changeRequest = PHAssetChangeRequest.creationRequestForAsset(from: UIImage(data: data)!)
        }

        guard let albumChangeRequest = PHAssetCollectionChangeRequest(for: album),
            let photoPlaceholder = changeRequest.placeholderForCreatedAsset else { return }

        placeholder = photoPlaceholder
        let fastEnumeration = NSArray(array: [photoPlaceholder] as [PHObjectPlaceholder])
        albumChangeRequest.addAssets(fastEnumeration)
    }, completionHandler: { success, error in
        guard let placeholder = placeholder else {
            completion?(nil)
            return
        }

        if success {
            let assets:PHFetchResult<PHAsset> =  PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
            let asset:PHAsset? = assets.firstObject
            completion?(asset)
        }
        else {
            completion?(nil)
        }
    })
}

func mergeImageData(imageData: Data, with metadata: NSDictionary) -> Data {
    let source: CGImageSource = CGImageSourceCreateWithData(imageData as NSData, nil)!
    let UTI: CFString = CGImageSourceGetType(source)!
    let newImageData =  NSMutableData()
    let cgImage = UIImage(data: imageData)!.cgImage
    let imageDestination: CGImageDestination = CGImageDestinationCreateWithData((newImageData as CFMutableData), UTI, 1, nil)!
    CGImageDestinationAddImage(imageDestination, cgImage!, metadata as CFDictionary)
    CGImageDestinationFinalize(imageDestination)

    return newImageData as Data
}