text:
Q: How do I make youtube api call to get categories according to given region and api key? I added this class to form1:
public class YoutubeApiResponse
        {
            public string kind { get; set; }
            public string etag { get; set; }
            public string nextPageToken { get; set; }
            public PageInfo pageInfo { get; set; }
            public List<Item> items { get; set; }
        }

The var Item not exist in the List
Then in form1 constructor I did:
using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
                if (response.IsSuccessStatusCode)
                {
                    var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
                }
            }

The api key is not valid api key, I just changed some letters random.
And in this part i'm getting error on the line:
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();

YoutubeApiResponse not exist so I changed it to YoutubeApiResponse but this doesn't have the Result property.
Another error on this line: Error   2   The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
And:
Error   1   'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method 'ReadAsAsync' accepting a first argument of type 'System.Net.Http.HttpContent' could be found (are you missing a using directive or an assembly reference?)
And the link that I'm using should be used to get the categories according to given region is: https://www.googleapis.com/youtube/v3/videoCategories?part=snippet&regionCode=IL&key=AIzaSyBgc1Gx-0tHbWp6-SWE0sQarpc6nGLtttt
In this example region code IL and api key.
I just not sure how to use it in my c# code.
This is my form1 code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Net.Http;
using System.Net.Http.Headers;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;

namespace Youtube_Manager
{

    public partial class Form1 : Form
    {
        List<string> results = new List<string>();
        string err1 = ""
        string userName = "someone@gmail.com";

        public Form1()
        {
            InitializeComponent();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
                if (response.IsSuccessStatusCode)
                {
                    var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
                }
            }

            UserCredential credential;
            using (FileStream stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None,
                    new FileDataStore("YouTube.Auth.Store")).Result;
            }
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });
            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22";
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "public";
            var filePath = @"C:\Users\bout0_000\Videos\test.mp4";//@"E:\video.mp4";
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {

                const int KB = 0x400;
                var minimumChunkSize = 256 * KB;

                var videosInsertRequest = youtubeService.Videos.Insert(video,
                    "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged +=
                    videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived +=
                    videosInsertRequest_ResponseReceived;
                // The default chunk size is 10MB, here will use 1MB.
                videosInsertRequest.ChunkSize = minimumChunkSize * 4;
                videosInsertRequest.Upload();
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video obj)
        {

        }

        private static void videosInsertRequest_ProgressChanged(IUploadProgress obj)
        {

        }

        private async Task Run()
        {
            UserCredential credential = null;
            using (var stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                try
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows for read-only access to the authenticated
                        // user's account, but not other types of account access.
                        new[] { YouTubeService.Scope.YoutubeReadonly },
                        "user",
                        CancellationToken.None,
                        new FileDataStore(this.GetType().ToString())
                    );
                }
                catch (Exception errrr)
                {
                    err1 = errrr.ToString();
                }
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var channelsListRequest = youtubeService.Channels.List("snippet,contentDetails");
            channelsListRequest.ForUsername = userName;
            var channelsListResponse = await channelsListRequest.ExecuteAsync();

            foreach (var channel in channelsListResponse.Items)
            {
                var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
                var nextPageToken = "";
                while (nextPageToken != null)
                {
                    var playlistRequest = youtubeService.Playlists.List("id,snippet,contentDetails,status,player");
                    playlistRequest.Id = uploadsListId;
                    playlistRequest.MaxResults = 50;
                    playlistRequest.PageToken = nextPageToken;
                    var playlistListResponse = await playlistRequest.ExecuteAsync();
                    if (playlistListResponse.Items.Count > 0)
                        MessageBox.Show(playlistListResponse.Items[0].Snippet.Title);

                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public class YoutubeApiResponse
        {
            public string kind { get; set; }
            public string etag { get; set; }
            public string nextPageToken { get; set; }
            public PageInfo pageInfo { get; set; }
            public List<Item> items { get; set; }
        }
    }
}

Using the part to get the categories according to given region id and add the categories later to a ComboBox as items that's i don't understand how to do.

A: Your mixing some things up.
Authenticate using a public API key:
 /// <summary>
        /// using Public APi key
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static YouTubeService AuthenticateOauth(string apiKey)
        {
            try
            {
                YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
                {
                    ApiKey = apiKey,
                    ApplicationName = "YouTube Data API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;
            }

        }

Authenticate
 var service = Authentication.AuthenticateOauth("xxxxx8wFajmmARCqp7YdqkLmd1XYx7c");

Make a request:
    var searchListRequest = service.Search.List("snippet");
    searchListRequest.Q = "Google"; // Replace with your search term.
    searchListRequest.MaxResults = 50;

    // Call the search.list method to retrieve results matching the specified query term.
    var searchListResponse = searchListRequest.Execute();

    List<string> videos = new List<string>();
    List<string> channels = new List<string>();
    List<string> playlists = new List<string>();

    // Add each result to the appropriate list, and then display the lists of
    // matching videos, channels, and playlists.
    foreach (var searchResult in searchListResponse.Items)
    {
        switch (searchResult.Id.Kind)
        {
            case "youtube#video":
                videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                break;

            case "youtube#channel":
                channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                break;

            case "youtube#playlist":
                playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                break;
        }
    }

}

code ripped from sample project Google-dotnet-samples Youtube
Update videoCatagories  example:
 var videoCatagories = service.VideoCategories.List("snippet");
 videoCatagories.RegionCode = "IL";
 var result = videoCatagories.Execute();


text:
Q: how to make one iteration per clock edge unlike all iterations in one clock edge the for loop in the following code is begin executed in one posedge clock.i want each iteration to occur at one clock edge so that at 5th clock edge my if will be activated.
begin
  temp_number3=contact;
    for(i3=0;i3<10;i3=i3+1)
     begin //for loop beign
     count3=i3;
     if(count3==5)
        begin //beign for if
        message=1;
         contact_num=temp_number3;
        end// end for if
    end // end of for loop
end

A: You do not need for-loop, but an always block that is active on posedge of clock, i.e.:
begin
    always@(posedge clk)
    begin
       if(count3 == 5) begin
          message <= 1;
          contact_num <= temp_number3;
          count3 <= count3 + 1;
       end else if(count 3 == 9) begin
          count3 <= 0;
          stopFlag <= 1;
       end else if(~stopFlag)
          count3 <= count3 + 1;
    end
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reliably overlay div (tooltip) above modal JQuery UI Dialog? I'm using CSS/Javascript to show tooltips for various inputs on mouseover. This works in a lot of various conditions but I'm having some trouble with inputs within a modal Jquery UI Dialog.
When I open the dialog the first time, it works 100% fine (tooltips show up in front of dialog), but if I close it and re-open it (without reloading the page), the tooltips will show up behind the dialog. I did explicitly set the z-index of tooltip div and dialog so that the tooltip has a higher value, but only works the first time .
If I set the dialog non-modal, everything is fine even when re-opening (but I highly prefer modal in this use case)
Note: Tested in Firefox 3.6.3
Any ideas on why it works only on first opening of dialog?
I have a helper div:

In which I'll append the actual tooltip:
jq('div#tool_tip_help_id').append('

');

CSS for tooltip div:
div.toolTipDiv{
    background-color:  #FFFF99;
    border-left: 1px solid gray;
    border-top: 1px solid gray;
    border-right: 3px solid gray;
    border-bottom: 3px solid gray;
    position: absolute;
    padding: 2px 2px 2px 2px;
        line-height: 120%;
    font-size: 12px;
    z-index: 100;
}

Relevant dialog declaration example:
jq("#Dialog").dialog( {
                bgiframe: true,
                autoOpen: false,
                width: 595,
                modal: true,
                draggable: false,
                zIndex: 1,
});

A: It does not work with a z-index of 1001 but it works with 1003.
As such, setting it to a very large value should work (100100).


text:
Q: How can I create an AttributeSet from a style.xml? Here's my story:
I got a custom ViewGroup that I want to create from code using a predefined style, my approach so far has been creating an AttributeSet object from a style.xml element, like so (warning, beware of the copy-paste code ahead):
    XmlPullParser parser = getResources().getXml(R.style.my_stylez);
    AttributeSet attributes = Xml.asAttributeSet(parser);

But when doing so I get some crazy error:
"..android.content.res.Resources$NotFoundException: Resource ID #0x7f090002 type #0x12 is not valid"
I'm know I'm probably missing something very obvious here (or am I?), and would be grateful if any of you guys can point me in the right direction.
Thanks

A: You need to start with a resource identifier for an XML file, preferably in res/xml. Then you can obtain an AttributeSet by first creating an XmlPullParser:
Resources res = context.getResources();
XmlPullParser parser = res.getXml(R.xml.some_xml_file);

// Seek to the first tag.
int type = 0;
while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
    type = parser.next();
}

// Wrap as an attribute set.
AttributeSet attrs = Xml.asAttributeSet(parser);

You can find examples of this in the drawable CTS tests in AOSP.

A: Looks like your XML(R.style.my_stylez) doesn't exist, or your R file is outdated.

A: Whenever you make new additions to the res directory it's a good idea to clean and build the project. But since ADT 15 this does not always work well. You sometimes have to go a step further and delete the bin directory as well as the gen directory.
After adt recreates those two directories, try running a clean again.

A: It seems pretty clear from looking around that it just isn't possible. Sorry. I truly wish this were possible...

A: The getXml method will read from res/xml, not from res/values, I think the idea is that you use one of the other other methods for getting the data, such as
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomTheme);

and then grab values out of the TypedArray:
thingColor = a.getColor(R.styleale.myCustomColor, res.getColor(R.color.myDefaultColor));

This works for styleables, however my problem is getting the AttributeSet attrs from XML in the first place to use as overrides, and allowing people to specify which XML file they want at run time, inflate it into an AttributeSet and pass it on.
I'll post back when I have an answer for the second part, but the code samples should solve


text:
Q: TWA app error: java.lang.NoClassDefFoundError i'm converting my pwa website to twa and i'm having some troubles.
when I try to sync or build the project i'm getting the following error:
FAILURE: Build failed with an exception.

*

*What went wrong:
java.lang.NoClassDefFoundError:

java.lang.NoClassDefFoundError (no error message)

I'm new to android and java, can someone helpme here?
I'm using bubblewrap/cli
my gradle:
import groovy.xml.MarkupBuilder  // ERROR : Cannot resolve symbol 'MarkupBuilder'

apply plugin: 'com.android.application'

def twaManifest = [
    applicationId: 'br.com.estudoon.www.twa',
    hostName: 'www.estudoon.com.br',
    launchUrl: '/login',
    name: 'Estudoon!',
    launcherName: 'OON!',
    themeColor: '#000000',
    navigationColor: '#000000',
    navigationColorDark: '#000000',
    navigationDividerColor: '#000000',
    navigationDividerColorDark: '#000000',
    backgroundColor: '#FFFFFF',
    enableNotifications: true,
    shortcuts: [],
    splashScreenFadeOutDuration: 300,
    generatorApp: 'bubblewrap-cli', // Application that generated the Android Project
    fallbackType: 'customtabs',
    enableSiteSettingsShortcut: 'true',
    orientation: 'any',
]

android {
    compileSdkVersion 30
    defaultConfig {
        applicationId "br.com.estudoon.www.twa"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        versionName "1"

        resValue "string", "appName", twaManifest.name

        resValue "string", "launcherName", twaManifest.launcherName

        def launchUrl = "https://" + twaManifest.hostName + twaManifest.launchUrl
        resValue "string", "launchUrl", launchUrl

            resValue "string", "webManifestUrl", 'https://www.estudoon.com.br/manifest.json'

        resValue "string", "hostName", twaManifest.hostName
twa#set_up_digital_asset_links_in_an_android_app
        resValue "string", "assetStatements",
                '[{ \\"relation\\": [\\"delegate_permission/common.handle_all_urls\\"],' +
                        '\\"target\\": {\\"namespace\\": \\"web\\", \\"site\\": \\"https://' +
                        twaManifest.hostName + '\\"}}]'

        resValue "color", "colorPrimary", twaManifest.themeColor

        resValue "color", "navigationColor", twaManifest.navigationColor

        resValue "color", "navigationColorDark", twaManifest.navigationColorDark

        resValue "color", "navigationDividerColor", twaManifest.navigationDividerColor

        resValue "color", "navigationDividerColorDark", twaManifest.navigationDividerColorDark

        resValue "color", "backgroundColor", twaManifest.backgroundColor

        resValue "string", "providerAuthority", twaManifest.applicationId + '.fileprovider'

        resValue "bool", "enableNotification", twaManifest.enableNotifications.toString()

        twaManifest.shortcuts.eachWithIndex { shortcut, index ->
            resValue "string", "shortcut_name_$index", "$shortcut.name"
            resValue "string", "shortcut_short_name_$index", "$shortcut.short_name"
        }
        resValue "integer", "splashScreenFadeOutDuration", twaManifest.splashScreenFadeOutDuration.toString()

        resValue "string", "generatorApp", twaManifest.generatorApp

        resValue "string", "fallbackType", twaManifest.fallbackType

        resValue "bool", "enableSiteSettingsShortcut", twaManifest.enableSiteSettingsShortcut
        resValue "string", "orientation", twaManifest.orientation
    }
    buildTypes {
        release {
            minifyEnabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

task generateShorcutsFile {
    assert twaManifest.shortcuts.size() < 5, "You can have at most 4 shortcuts."
    twaManifest.shortcuts.eachWithIndex { s, i ->
        assert s.name != null, 'Missing `name` in shortcut #' + i
        assert s.short_name != null, 'Missing `short_name` in shortcut #' + i
        assert s.url != null, 'Missing `icon` in shortcut #' + i
        assert s.icon != null, 'Missing `url` in shortcut #' + i
    }

    def shortcutsFile = new File("$projectDir/src/main/res/xml", "shortcuts.xml")

    def xmlWriter = new StringWriter()
    def xmlMarkup = new MarkupBuilder(new IndentPrinter(xmlWriter, "    ", true))

    xmlMarkup
        .'shortcuts'('xmlns:android': 'http://schemas.android.com/apk/res/android') {
            twaManifest.shortcuts.eachWithIndex { s, i ->
                'shortcut'(
                        'android:shortcutId': 'shortcut' + i,
                        'android:enabled': 'true',
                        'android:icon': '@drawable/' + s.icon,
                        'android:shortcutShortLabel': '@string/shortcut_short_name_' + i,
                        'android:shortcutLongLabel': '@string/shortcut_name_' + i) {
                    'intent'(
                            'android:action': 'android.intent.action.MAIN',
                            'android:targetPackage': twaManifest.applicationId,
                            'android:targetClass': twaManifest.applicationId + '.LauncherActivity',
                            'android:data': s.url)
                    'categories'('android:name': 'android.intent.category.LAUNCHER')
                }
            }
        }
    shortcutsFile.text = xmlWriter.toString() + '\n'
}

preBuild.dependsOn(generateShorcutsFile)

repositories {

}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.2.0'

}

EDIT:
I'm getting the same error with any project, even the ones bult in android studio.
Alread reinstalled android studio, XAMPP, java and node.

A: For Cannot resolve symbol MarkupBuilder: Add the groovy classpath to your build.gradle file in the root folder if you are using gradle 7
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0'
        classpath 'org.codehaus.groovy:groovy-xml:3.0.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        mavenCentral()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}


text:
Q: AES decryption in PHP I have a base64 encrypted string that I need to decrypt using PHP, the encrypted string was generated by a flash application I reversed and I found it uses AES. The problem is that I don't know if the AES implementation I got is a standard I can replicate in PHP. It would be better if there is a PHP class I can use without installing mcrypt.
Here is an example of what the flash application does to decrypt the string:
var encrypted:String = AES.encrypt("hello world","my great key",AES.BIT_KEY_256); // "06/0/6Ojo6ObeIEZaHcxAinbjD=="
// I need to do this in php
var decrypted:String = AES.decrypt("06/0/6Ojo6ObeIEZaHcxAinbjD==","my great key",AES.BIT_KEY_256); // "hello world"

The reversed AES class:
public class AES {

    public static const BIT_KEY_128:int = 128;
    public static const BIT_KEY_192:int = 192;
    public static const BIT_KEY_256:int = 0x0100;
    private static const SBOX:Array = [
        99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 0xFF, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22];
    private static const RCON:Array = [
        [0, 0, 0, 0],
        [1, 0, 0, 0],
        [2, 0, 0, 0],
        [4, 0, 0, 0],
        [8, 0, 0, 0],
        [16, 0, 0, 0],
        [32, 0, 0, 0],
        [64, 0, 0, 0],
        [128, 0, 0, 0],
        [27, 0, 0, 0],
        [54, 0, 0, 0]
    ];

    public static function encrypt(_arg1:String, _arg2:String, _arg3:int):String {
        var _local19:int;
        var _local20:Array;
        var _local21:int;
        var _local22:Array;
        var _local4 = 16;
        if (!(((((_arg3 == BIT_KEY_128)) || ((_arg3 == BIT_KEY_192)))) || ((_arg3 == BIT_KEY_256)))) {
            throw (new Error("Must be a key mode of either 128, 192, 256 bits"));
        }
        ;
        _arg1 = Utf8.encode(_arg1);
        _arg2 = Utf8.encode(_arg2);
        var _local5:int = (_arg3 / 8);
        var _local6:Array = new Array(_local5);
        var _local7:int;
        while (_local7 < _local5) {
            _local6[_local7] = ((isNaN(_arg2.charCodeAt(_local7))) ? 0 : _arg2.charCodeAt(_local7));
            _local7++;
        }
        ;
        var _local8:Array = cipher(_local6, keyExpansion(_local6));
        _local8 = cipher(_local6, keyExpansion(_local6)).concat(_local8.slice(0, (_local5 - 16)));
        var _local9:Array = new Array(_local4);
        var _local10:int = new Date().getTime();
        var _local11:int = Math.floor((_local10 / 1000));
        var _local12:int = (_local10 % 1000);
        _local7 = 0;
        while (_local7 < 4) {
            _local9[_local7] = ((_local11 >>> (_local7 * 8)) & 0xFF);
            _local7++;
        }
        ;
        _local7 = 0;
        while (_local7 < 4) {
            _local9[(_local7 + 4)] = (_local12 & 0xFF);
            _local7++;
        }
        ;
        var _local13 = "";
        _local7 = 0;
        while (_local7 < 8) {
            _local13 = (_local13 + String.fromCharCode(_local9[_local7]));
            _local7++;
        }
        ;
        var _local14:Array = keyExpansion(_local8);
        var _local15:int = Math.ceil((_arg1.length / _local4));
        var _local16:Array = new Array(_local15);
        var _local17:int;
        while (_local17 < _local15) {
            _local19 = 0;
            while (_local19 < 4) {
                _local9[(15 - _local19)] = ((_local17 >>> (_local19 * 8)) & 0xFF);
                _local19++;
            }
            ;
            _local19 = 0;
            while (_local19 < 4) {
                _local9[((15 - _local19) - 4)] = ((_local17 / 4294967296) >>> (_local19 * 8));
                _local19++;
            }
            ;
            _local20 = cipher(_local9, _local14);
            _local21 = (((_local17 < (_local15 - 1))) ? _local4 : (((_arg1.length - 1) % _local4) + 1));
            _local22 = new Array(_local21);
            _local7 = 0;
            while (_local7 < _local21) {
                _local22[_local7] = (_local20[_local7] ^ _arg1.charCodeAt(((_local17 * _local4) + _local7)));
                _local22[_local7] = String.fromCharCode(_local22[_local7]);
                _local7++;
            }
            ;
            _local16[_local17] = _local22.join("");
            _local17++;
        }
        ;
        var _local18:String = (_local13 + _local16.join(""));
        _local18 = Base64.encode(_local18);
        return (_local18);
    }

    public static function decrypt(_arg1:String, _arg2:String, _arg3:int):String {
        var _local16:int;
        var _local18:int;
        var _local19:Array;
        var _local20:Array;
        var _local4 = 16;
        if (!(((((_arg3 == BIT_KEY_128)) || ((_arg3 == BIT_KEY_192)))) || ((_arg3 == BIT_KEY_256)))) {
            throw (new Error("Must be a key mode of either 128, 192, 256 bits"));
        }
        ;
        _arg1 = Base64.decode(_arg1);
        _arg2 = Utf8.encode(_arg2);
        var _local5:int = (_arg3 / 8);
        var _local6:Array = new Array(_local5);
        var _local7:int;
        while (_local7 < _local5) {
            _local6[_local7] = ((isNaN(_arg2.charCodeAt(_local7))) ? 0 : _arg2.charCodeAt(_local7));
            _local7++;
        }
        ;
        var _local8:Array = cipher(_local6, keyExpansion(_local6));
        _local8 = cipher(_local6, keyExpansion(_local6)).concat(_local8.slice(0, (_local5 - 16)));
        var _local9:Array = new Array(8);
        var _local10:String = _arg1.slice(0, 8);
        _local7 = 0;
        while (_local7 < 8) {
            _local9[_local7] = _local10.charCodeAt(_local7);
            _local7++;
        }
        ;
        var _local11:Array = keyExpansion(_local8);
        var _local12:int = Math.ceil(((_arg1.length - 8) / _local4));
        var _local13:Array = new Array(_local12);
        _local16 = 0;
        while (_local16 < _local12) {
            _local13[_local16] = _arg1.slice((8 + (_local16 * _local4)), ((8 + (_local16 * _local4)) + _local4));
            _local16++;
        }
        ;
        var _local14:Array = _local13;
        var _local15:Array = new Array(_local14.length);
        _local16 = 0;
        while (_local16 < _local12) {
            _local18 = 0;
            while (_local18 < 4) {
                _local9[(15 - _local18)] = ((_local16 >>> (_local18 * 8)) & 0xFF);
                _local18++;
            }
            ;
            _local18 = 0;
            while (_local18 < 4) {
                _local9[((15 - _local18) - 4)] = (((((_local16 + 1) / 4294967296) - 1) >>> (_local18 * 8)) & 0xFF);
                _local18++;
            }
            ;
            _local19 = cipher(_local9, _local11);
            _local20 = new Array(String(_local14[_local16]).length);
            _local7 = 0;
            while (_local7 < String(_local14[_local16]).length) {
                _local20[_local7] = (_local19[_local7] ^ String(_local14[_local16]).charCodeAt(_local7));
                _local20[_local7] = String.fromCharCode(_local20[_local7]);
                _local7++;
            }
            ;
            _local15[_local16] = _local20.join("");
            _local16++;
        }
        ;
        var _local17:String = _local15.join("");
        _local17 = Utf8.decode(_local17);
        return (_local17);
    }

    private static function cipher(_arg1:Array, _arg2:Array):Array {
        var _local3 = 4;
        var _local4:int = ((_arg2.length / _local3) - 1);
        var _local5:Array = [
            [],
            [],
            [],
            []
        ];
        var _local6:int;
        while (_local6 < (4 * _local3)) {
            _local5[(_local6 % 4)][Math.floor((_local6 / 4))] = _arg1[_local6];
            _local6++;
        }
        ;
        _local5 = addRoundKey(_local5, _arg2, 0, _local3);
        var _local7 = 1;
        while (_local7 < _local4) {
            _local5 = subBytes(_local5, _local3);
            _local5 = shiftRows(_local5, _local3);
            _local5 = mixColumns(_local5);
            _local5 = addRoundKey(_local5, _arg2, _local7, _local3);
            _local7++;
        }
        ;
        _local5 = subBytes(_local5, _local3);
        _local5 = shiftRows(_local5, _local3);
        _local5 = addRoundKey(_local5, _arg2, _local4, _local3);
        var _local8:Array = new Array((4 * _local3));
        var _local9:int;
        while (_local9 < (4 * _local3)) {
            _local8[_local9] = _local5[(_local9 % 4)][Math.floor((_local9 / 4))];
            _local9++;
        }
        ;
        return (_local8);
    }

    private static function keyExpansion(_arg1:Array):Array {
        var _local8:Array;
        var _local9:int;
        var _local2 = 4;
        var _local3:int = (_arg1.length / 4);
        var _local4:int = (_local3 + 6);
        var _local5:Array = new Array((_local2 * (_local4 + 1)));
        var _local6:Array = new Array(4);
        var _local7:int;
        while (_local7 < _local3) {
            _local8 = [_arg1[(4 * _local7)], _arg1[((4 * _local7) + 1)], _arg1[((4 * _local7) + 2)], _arg1[((4 * _local7) + 3)]];
            _local5[_local7] = _local8;
            _local7++;
        }
        ;
        _local7 = _local3;
        while (_local7 < (_local2 * (_local4 + 1))) {
            _local5[_local7] = new Array(4);
            _local9 = 0;
            while (_local9 < 4) {
                _local6[_local9] = _local5[(_local7 - 1)][_local9];
                _local9++;
            }
            ;
            if ((_local7 % _local3) == 0) {
                _local6 = subWord(rotWord(_local6));
                _local9 = 0;
                while (_local9 < 4) {
                    _local6[_local9] = (_local6[_local9] ^ RCON[(_local7 / _local3)][_local9]);
                    _local9++;
                }
                ;
            } else {
                if ((((_local3 > 6)) && (((_local7 % _local3) == 4)))) {
                    _local6 = subWord(_local6);
                }
                ;
            }
            ;
            _local9 = 0;
            while (_local9 < 4) {
                _local5[_local7][_local9] = (_local5[(_local7 - _local3)][_local9] ^ _local6[_local9]);
                _local9++;
            }
            ;
            _local7++;
        }
        ;
        return (_local5);
    }

    private static function subBytes(_arg1:Array, _arg2:int):Array {
        var _local4:int;
        var _local3:int;
        while (_local3 < 4) {
            _local4 = 0;
            while (_local4 < _arg2) {
                _arg1[_local3][_local4] = SBOX[_arg1[_local3][_local4]];
                _local4++;
            }
            ;
            _local3++;
        }
        ;
        return (_arg1);
    }

    private static function shiftRows(_arg1:Array, _arg2:int):Array {
        var _local5:int;
        var _local3:Array = new Array(4);
        var _local4 = 1;
        while (_local4 < 4) {
            _local5 = 0;
            while (_local5 < 4) {
                _local3[_local5] = _arg1[_local4][((_local5 + _local4) % _arg2)];
                _local5++;
            }
            ;
            _local5 = 0;
            while (_local5 < 4) {
                _arg1[_local4][_local5] = _local3[_local5];
                _local5++;
            }
            ;
            _local4++;
        }
        ;
        return (_arg1);
    }

    private static function mixColumns(_arg1:Array):Array {
        var _local3:Array;
        var _local4:Array;
        var _local5:int;
        var _local2:int;
        while (_local2 < 4) {
            _local3 = new Array(4);
            _local4 = new Array(4);
            _local5 = 0;
            while (_local5 < 4) {
                _local3[_local5] = _arg1[_local5][_local2];
                _local4[_local5] = (((_arg1[_local5][_local2] & 128)) ? ((_arg1[_local5][_local2] << 1) ^ 283) : (_arg1[_local5][_local2] << 1));
                _local5++;
            }
            ;
            _arg1[0][_local2] = ((((_local4[0] ^ _local3[1]) ^ _local4[1]) ^ _local3[2]) ^ _local3[3]);
            _arg1[1][_local2] = ((((_local3[0] ^ _local4[1]) ^ _local3[2]) ^ _local4[2]) ^ _local3[3]);
            _arg1[2][_local2] = ((((_local3[0] ^ _local3[1]) ^ _local4[2]) ^ _local3[3]) ^ _local4[3]);
            _arg1[3][_local2] = ((((_local3[0] ^ _local4[0]) ^ _local3[1]) ^ _local3[2]) ^ _local4[3]);
            _local2++;
        }
        ;
        return (_arg1);
    }

    private static function addRoundKey(_arg1:Array, _arg2:Array, _arg3:int, _arg4:int):Array {
        var _local6:int;
        var _local5:int;
        while (_local5 < 4) {
            _local6 = 0;
            while (_local6 < _arg4) {
                _arg1[_local5][_local6] = (_arg1[_local5][_local6] ^ _arg2[((_arg3 * 4) + _local6)][_local5]);
                _local6++;
            }
            ;
            _local5++;
        }
        ;
        return (_arg1);
    }

    private static function subWord(_arg1:Array):Array {
        var _local2:int;
        while (_local2 < 4) {
            _arg1[_local2] = SBOX[_arg1[_local2]];
            _local2++;
        }
        ;
        return (_arg1);
    }

    private static function rotWord(_arg1:Array):Array {
        var _local2:int = _arg1[0];
        var _local3:int;
        while (_local3 < 3) {
            _arg1[_local3] = _arg1[(_local3 + 1)];
            _local3++;
        }
        ;
        _arg1[3] = _local2;
        return (_arg1);
    }

}

The above code is part of a flash tool I use in my app, now I need to replicate this in the server decrypting a URL that was encrypted by this AES algorithm, it's not password hacking(who uses aes for paswords and a known key) nor asking for a tool, it's understanding the AES implementation and reproduce the same behavior in PHP.
I tried phpseclib but I cannot produce the same output I get using the Actionscript code, I played with the lib but my output is always different. Following the previous example, in AS encrypting the text hello world with the key my great key I get 06/0/6Ojo6ObeIEZaHcxAinbjD==, then in PHP I try something like:
$cipher = new Crypt_AES();
$cipher->setKeyLength(256);
$cipher->setKey('my great key');
echo base64_encode($cipher->encrypt('hello world'));

and it prints v/Uc20nSNRNnJr0D15wBzA==.

A: To decode the base 64, you can use base64_decode to decode the string into the raw bytes.  For decryption, this library (phpseclib) seems to be ok.  They have examples on how to set up everything here.  It can optionally use mcrypt, but won't if you don't have it.


text:
Q: Execute echo command within a Python script I am trying to execute an echo command within a python script.
If I do it in the terminal, it looks like this:
echo -n -e '{"DATE": "Wednesday, May 04, 2016", "message": "ADIsss     ", "INDEX_CLOSING_VALUE": "4428.61"}'"\0" | nc -w0 127.0.0.1 12201

I tried using:

import subprocess
cmd = '''echo -n -e '{ "version": "1.1", "host": "example.org", "short_message": "A short message", "level": 5, "_some_info": "foo" }'"\0" | nc -w0 127.0.0.1 12201'''
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
print proc.communicate()[0],

i got a error :
Traceback (most recent call last):
  File "tet.py", line 3, in <module>
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

how can I solve this with subprocess in python

A: Try using os module
import os
os.system("echo...........")

If you want to use variables here, you need to add here with out in quotation marks
for example
import os
string="This is test"
os.system("echo "+string+">> ~/Desktop/file.txt")

This code will append string "This is test" to the file.txt in Desktop location


text:
Q: Loading data into Google Big Query without binary format Can you load csv file without opening in binary format
with open(file_path, "rb") as source_file:
job = client.load_table_from_file(source_file, table_id, job_config=job_config)

A: It looks like Google bigquery will not handle special characters when loading data from csv local storage that contains special characters


text:
Q: error: [Dagger/DependencyCycle] Found a dependency cycle error after using ActivityRetainedScoped I am working on app that uses MVVM, Room and dagger hilt, I have implemented first part that handle server response, remote DataSource, viewmodel and all this stuff, and it's worked fine, but after I implemented the database module, I got this error when I tried to build
public abstract static class SingletonC implements BaseApplication_GeneratedInjector,
                         ^
      com.test.dummyappv3.data.database.ItemDAO is injected at
          com.test.dummyappv3.di.DatabaseModule.provideDao(itemDAO)
      com.test.dummyappv3.data.database.ItemDAO is injected at
          com.test.dummyappv3.data.LocalDataSource(itemDAO)
      com.test.dummyappv3.data.LocalDataSource is injected at
          com.test.dummyappv3.data.Repository(�, localDataSource)
      com.test.dummyappv3.data.Repository is injected at
          com.test.dummyappv3.viewmodels.PostViewModel(repository)
      com.test.dummyappv3.viewmodels.PostViewModel is injected at
          com.test.dummyappv3.viewmodels.PostViewModel_HiltModules.BindsModule.binds(vm)
      @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
          dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.test.dummyappv3.BaseApplication_HiltComponents.SingletonC ? com.test.dummyappv3.BaseApplication_HiltComponents.ActivityRetainedC ? com.test.dummyappv3.BaseApplication_HiltComponents.ViewModelC]

and I think it's related with ActivityRetainedScoped in Repository Class
@ActivityRetainedScoped
public class Repository {

    public RemoteDataSource remoteDataSource;
    public LocalDataSource localDataSource;

    @Inject
    public Repository(RemoteDataSource remoteDataSource, LocalDataSource localDataSource) {
        this.remoteDataSource = remoteDataSource;
        this.localDataSource = localDataSource;
    }
}

DatabaseModule
@InstallIn(SingletonComponent.class)
@Module
public class DatabaseModule {

    @Singleton
    @Provides
    public static ItemsDatabase provideDatabase(@ApplicationContext Context context){
        return Room.databaseBuilder(context,ItemsDatabase.class,"items_database")
                .fallbackToDestructiveMigration()
                .build();

    }

    @Singleton
    @Provides
    public static ItemDAO provideDao(ItemDAO itemDAO){
        return itemDAO;
    }
}

RemoteDataSource
    private final PostAPIService postAPIService;

    @Inject
    public RemoteDataSource(PostAPIService postAPIService) {
        this.postAPIService = postAPIService;
    }

    public Observable<PostList> getPostList(String URL) {
        return postAPIService.getPostList(URL);
    }

    public Observable<PostList> getPostListByLabel(String URL) {
        return postAPIService.getPostListByLabel(URL);
    }

}

LocalDataSource
public class LocalDataSource {

    private final ItemDAO itemDAO;

    @Inject
    public LocalDataSource(ItemDAO itemDAO) {
        this.itemDAO = itemDAO;
    }

    public Completable insertItem(Item item){
        return itemDAO.insert(item);
    }

    public Flowable<List<Item>> getAlItems(){
        return itemDAO.getAlItems();
    }

}

and finally the viewmodel
@HiltViewModel
public class PostViewModel extends ViewModel {

    public static final String TAG = "PostViewModel";

    private Repository repository = null;
    public MutableLiveData<PostList> postListMutableLiveData = new MutableLiveData<>();
    public MutableLiveData<String> finalURL = new MutableLiveData<>();
    public MutableLiveData<String> token = new MutableLiveData<>();
    public MutableLiveData<String> label = new MutableLiveData<>();

    public MutableLiveData<Boolean> ifAnythingWrongHappened = new MutableLiveData<>();

    @Inject
    public PostViewModel(Repository repository) {
        this.repository = repository;
    }

    public final LiveData<List<Item>> getAllPostsFromDB
            = LiveDataReactiveStreams.fromPublisher(repository.localDataSource.getAlItems());

    @SuppressLint("CheckResult")
    public void getPosts() {
        ifAnythingWrongHappened.setValue(false);
        Log.e(TAG, finalURL.getValue());

        repository.remoteDataSource.getPostList(finalURL.getValue())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PostList>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull PostList postList) {
                        Log.e(TAG, postList.getNextPageToken());
                        token.setValue(postList.getNextPageToken());
                        postListMutableLiveData.setValue(postList);
                        for (int i = 0; i < postList.getItems().size(); i++) {
                            repository.localDataSource.insertItem(postList.getItems().get(i))
                                    .subscribeOn(Schedulers.computation())
                                    .subscribe(new CompletableObserver() {
                                        @Override
                                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                                        }

                                        @Override
                                        public void onComplete() {

                                        }

                                        @Override
                                        public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                                            Log.e(TAG, "onError: "+e.getMessage() );
                                            ifAnythingWrongHappened.setValue(true);
                                        }
                                    });
                        }
                        finalURL.setValue(finalURL.getValue() + "&pageToken=" + token.getValue());

                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        Log.e(TAG, e.getMessage() + e.getCause());
                        ifAnythingWrongHappened.setValue(true);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
}

I tried to delete this @ActivityRetainedScoped and @ApplicationContext but the same error also I tried the @ViewModelScoped in the viewmodel

A:     @Singleton
    @Provides
    public static ItemDAO provideDao(ItemDAO itemDAO){
        return itemDAO;
    }

This is the circular dependency.  The important part of that error trace to look at is everything from the first entry (ItemDAO) up to and excluding the second appearance of that same class.  The rest of the error message is showing one use of ItemDAO in the dependency graph, since Dagger only validates reachable dependencies.
I assume you intended to do something like this instead:
    @Singleton
    @Provides
    public static ItemDAO provideDao(ItemsDatabase database){
        return database.itemDAO();
    }


text:
Q: Build terms_set query in elasticsearch java api I try to find out how to build the following query with elasticsearch java api
{
  "query": {
    "bool": {
      "must": [
        {
          "terms_set": {
            "names": {
              "minimum_should_match_field": "some_match_field",
              "terms": [
                "Ala",
                "Bob"
              ]
            }
          }
        }
      ]
    }
  }
}

I tried to build this query with following code, but there is no termsSetQuery method as well as minimumShouldMatchField in api.
        NativeSearchQuery build = new NativeSearchQueryBuilder()
            .withQuery(boolQuery()
                    .must(termsQuery("names", List.of("Ala", "Bob"))))
            .build();

but it results as below
{
  "bool": {
    "must": [
      {
        "terms": {
          "names": [
            "Ala",
            "Bob"
          ]
        }
      }
    ]
  }
}

A: You need to use TermsSetQueryBuilder for creating query like below:
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
List<String> terms = new ArrayList<>();
terms.add("Ala");
searchSourceBuilder.query(QueryBuilders.boolQuery()
                .must(new TermsSetQueryBuilder("names", terms).setMinimumShouldMatchField("some_match_field")));


text:
Q: Use a template with macro on content type I'm using Sharepoint 2013 and have some content type with word template.
I need to add a macro on open document in my template.
When i add my macro and save in dotm my template. The document generated from this template cannot be opened.
How can i have a template with macro?
Thanks

A: I finally found a solution, i used a template with extension .dotm


text:
Q: Validate object with static and dynamic keys I am trying to write a Yup validation schema of an object that it's Type looks like this
interface myObject {
  prop0: Date
  prop1: {
    nestedProp1: string
    nestedProp2: number
    [key: string]: string | number
  }
}

i tried this:
yup.object({
  prop0: yup.string(),
  prop1: yup.object({
    nestedProp1: yup.string(),
    nestedProp2: yup.number(),
    // here goes the dynamic type validation ???
  })
})

im not able to write the correct validation for the dynamic key in prop1.
EDIT:
What im trying to achieve is basically feeding this type as a generic type for a function, and get it's schema using SchemaOf so i can type another param in this function (where i input my schema)
Here is a link to sandbox where im mimicking the real case scenario.
You can see that TS is complaining in line 39.

A: Solution was simple.. i forgot to put .shape() in the yup validation for objects..


text:
Q: How to solve ClassCastException when passing date parameters to jasper report? I have a report with between date parameters on derby database
and I have got below message when sending dates through two text fields to run i
to got below quote error msg.

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
  java.lang.String cannot be cast to java.util.Date     at
  net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.setDate(JRJdbcQueryExecuter.java:615)

My code to call jasper report is here:
public void runREport() {
   try {
       Connection con1= null;

       String Op=jTsubmain_no.getText();
       int val = Integer.parseInt((String) Op.trim());
       Map param1 = new HashMap();
       param1.put("sub_no",val);
       param1.put("fdate",jTfdate.getText());
       param1.put("ldate",jTldate.getText());

       try {
              con1= DriverManager.getConnection("jdbc:derby://localhost:1527//accountsdb","accounts","accounts");
       } catch (SQLException ex) {
              Logger.getLogger(reports.class.getName()).log(Level.SEVERE, null, ex);
       }

       String jrxmlFileName = "C:/Users/hosam/Documents/NetBeansProjects/Accsys/src/accsys/report2.jrxml";
      JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFileName);
      JasperReport jasperReport =JasperCompileManager.compileReport(jasperDesign);
      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param1, con1);
      JasperViewer.viewReport(jasperPrint);
   } catch (JRException ex) {
           JOptionPane.showMessageDialog( null,  ex);
   }
}

A: You have a different class between parameter passed and definition in jrxml.
jTfdate.getText() is returning an object of type java.lang.String
in jrxml you have this definition of parameter
<parameter name="fdate" class="java.util.Date">
    <defaultValueExpression><![CDATA[""]]></defaultValueExpression>
</parameter>

Solution, pass a java.util.Date object in your parameter map.
Example
param1.put("fdate",new SimpleDateFormat("yourPattern").parse(jTfdate.getText()));

Where the pattern, "yourPattern" should correspond to the text parsed see SimpleDateFormat pattern's.
How to catch the ParseException and set default value, I leave to you.


text:
Q: Как объединить несколько значений в одну строку? Начинаю изучать Objective-C (после Java) и столкнулся с такой проблемой: не знаю, как форматировать строку, конвертировать типы и объединить строки.
В общем, хочу вывести примерно такую строку (как бы это выглядело на Java):
 return "const value" + intVariable + stringVariable;

A: С использованием NSString:
NSString *string1 = [NSString stringWithFormat:@"%@%d", @"constant string", 12345];

Собственно, суть та же, что и обычный sprintf. Но есть огромный плюс — длину за Вас посчитают!
Тут всё есть :).
A: Я никогда в жизни не встречался с objective-c, но предполагаю, что там всё так же как и в обычном C :).
Если не использовать никакой специальный класс для строк, а обходиться только char*, то примерно так:
char *result = new char[1024];
sprintf(result, "%s%d%s", "const value", intVariable, stringVariable);

Собственно, что делает этот код:
Во-первых, мы заводим буфер, в который положим итоговую строку. Число 1024 — это я из головы взял. Главное, чтобы места хватило. Скорее всего, имеет смысл вычислить его как длину Вашей константной строки плюс strlen(stringVariable) плюс несколько символов, чтобы число точно влезло.
Далее, используем функцию sprintf (чтобы её заполучить надо включить stdio.h). Она кладёт в свой первый аргумент строку, соответствующую формату, указанному вторым аргументом, собрав её из всех остальных. Этот самый страшный printf-формат используется очень много где, так что с ним полезно быть знакомым :)


text:
Q: Spring boot websockets listener add parameter I am implementing a chat room with webscoket by Spring boot
This is the code
ChatMessage.Class
public class ChatMessage {
    private MessageType type;
    private String content;
    private String sender;

    public enum MessageType {
        CHAT,
        JOIN,
        LEAVE
    }

    public MessageType getType() {
        return type;
    }

    public void setType(MessageType type) {
        this.type = type;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

}

My WebSocketConfig.Class
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }
}

WebSocketListener.Class
@Component
public class WebSocketEventListener {

    @Autowired
    private SimpMessageSendingOperations messagingTemplate;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        System.out.println("Received a new web socket connection");
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

        String username = (String) headerAccessor.getSessionAttributes().get("username");
        if (username != null) {

            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(ChatMessage.MessageType.LEAVE);
            chatMessage.setSender(username);
            messagingTemplate.convertAndSend("/topic/public", chatMessage);
        }
    }
}

ChatController:
@Controller
public class ChatController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/chat.sendMessage/{room}")
    public void sendMessage(@Payload ChatMessage chatMessage, @DestinationVariable String room) {
        simpMessagingTemplate.convertAndSend("/topic/public/"+room, chatMessage);
    }

    @MessageMapping("/chat.addUser/{room}")
    public void addUser(@Payload ChatMessage chatMessage,
                               SimpMessageHeaderAccessor headerAccessor, @DestinationVariable String room) {
        // Add username in web socket session
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        simpMessagingTemplate.convertAndSend("/topic/public/"+room, chatMessage);
    }
}

My Index.html:
    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Spring Boot WebSocket Chat Application</title>
    <link rel="stylesheet" href="/css/main.css" />

Sorry! Your browser doesn't support Javascript

Type your username

        <form id="usernameForm" name="usernameForm">

                <input type="text" id="name" placeholder="Username" autocomplete="off" class="form-control" />

                <input type="text" id="room_num" placeholder="RoomNum" autocomplete="off" class="form-control"/>

                <button type="submit" class="accent username-submit">Start Chatting</button>

        </form>

Spring WebSocket Chat Demo

            Connecting...

        <form id="messageForm" name="messageForm">

                    <input type="text" id="message" placeholder="Type a message..." autocomplete="off" class="form-control"/>
                    <button type="submit" class="primary">Send</button>

        </form>

main.js:
    'use strict';

var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');

var stompClient = null;
var username = null;
var room_num = null;

var colors = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];

function connect(event) {
    username = document.querySelector('#name').value.trim();
    room_num = document.querySelector('#room_num').value.trim();
    if(username) {
        usernamePage.classList.add('hidden');
        chatPage.classList.remove('hidden');

        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);

        stompClient.connect({}, onConnected, onError);
    }
    event.preventDefault();
}

function onConnected() {
    // Subscribe to the Public Topic
    stompClient.subscribe('/topic/public/'+room_num, onMessageReceived);

    // Tell your username to the server
    stompClient.send("/app/chat.addUser/"+room_num,
        {},
        JSON.stringify({sender: username, type: 'JOIN'})
    );

    connectingElement.classList.add('hidden');
}

function onError(error) {
    connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
    connectingElement.style.color = 'red';
}

function sendMessage(event) {
    var messageContent = messageInput.value.trim();
    if(messageContent && stompClient) {
        var chatMessage = {
            sender: username,
            content: messageInput.value,
            type: 'CHAT'
        };
        stompClient.send("/app/chat.sendMessage/"+room_num, {}, JSON.stringify(chatMessage));
        messageInput.value = '';
    }
    event.preventDefault();
}

function onMessageReceived(payload) {
    var message = JSON.parse(payload.body);

    var messageElement = document.createElement('li');

    if(message.type === 'JOIN') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' joined!';
    } else if (message.type === 'LEAVE') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' left!';
    } else {
        messageElement.classList.add('chat-message');

        var avatarElement = document.createElement('i');
        var avatarText = document.createTextNode(message.sender[0]);
        avatarElement.appendChild(avatarText);
        avatarElement.style['background-color'] = getAvatarColor(message.sender);

        messageElement.appendChild(avatarElement);

        var usernameElement = document.createElement('span');
        var usernameText = document.createTextNode(message.sender);
        usernameElement.appendChild(usernameText);
        messageElement.appendChild(usernameElement);
    }

    var textElement = document.createElement('p');
    var messageText = document.createTextNode(message.content);
    textElement.appendChild(messageText);

    messageElement.appendChild(textElement);

    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}

function getAvatarColor(messageSender) {
    var hash = 0;
    for (var i = 0; i < messageSender.length; i++) {
        hash = 31 * hash + messageSender.charCodeAt(i);
    }
    var index = Math.abs(hash % colors.length);
    return colors[index];
}

usernameForm.addEventListener('submit', connect, true)
messageForm.addEventListener('submit', sendMessage, true)

I want to realize that multiple chat rooms exist at the same time, So i do not use the @Sendto
I define a input room_num to indicate the number of the chat room
In js file, use stompClient.send("/app/chat.sendMessage/"+room_num, {}, JSON.stringify(chatMessage)); to send message.
In Controller, use simpMessagingTemplate.convertAndSend("/topic/public/"+room, chatMessage); receive message from different chatroom
But this way of stitching url will produce a lot hard code
Is there any good alternative?
When the user leaves the chat room, handleWebSocketDisconnectListener use messagingTemplate.convertAndSend("/topic/public", chatMessage); to notify users in a same chatroom, someone leave this room,
but the url should be /topic/public/room_num.
However, this is a DisconnectListener, It will listen for all closed connections,
I want to realize that when the user leaves a chat room, only notify the users in the same chat room that the user has left


text:
Q: read data in specific column and row of a text file I Have a text file which contain 3 columns and 20000 rows.
I like to know what should I do to get the specific data (for example) in row 1000 and column 2?
My first column is formatted like AAAA and my second column is a number like 1234.
I tried this solution but I got an error based on my first column being letters
I would like to define a variable which contains my data at the end:
with open ('my_file') as f:
    for x , line in eumerate(f):
         if x = 1000:
             numfloat = map(float , line.split())
             print numfloat[1]

A: You are trying to use float() on something that contains letters.  this happens when you call:
numfloat = map(float , line.split())

You need to tell us the exact output that you are looking for but here is one possible solution
num_float = map(float, line.split()[1])

or better yet

num_float = float(line.split()[1])

This will only get you the middle column, I'm not certain if you need the entire row or not.
Additionally, as noted below, you need to change = to == in your if statement.  = is for assigment, == is for comparison.

A: make '=' to '==' at line 3 of your code
with open('my_file', 'r') as f:
    for x, line in enumerate(f):
        if x == 1000:
            print float(line.split()[1])

A: import re

with open('my_file', 'r') as f:
    for x, line in enumerate(f):
        if x == 1000:
            array = re.split('(\d+)',line) # array=['AAAA','123'] if line='AAAA123'
            print array[1] # your required second row.


text:
Q: How to use C# example using JsonPath? I'm trying to use JsonPath for .NET (http://code.google.com/p/jsonpath/downloads/list) and I'm having trouble finding an example of how to parse a Json string and a JsonPath string and get a result.
Has anyone used this?

A: using Newtonsoft.Json.Linq yo can use function SelectToken and try out yous JsonPath
Check documentation https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm
Object jsonObj = JObject.Parse(stringResult);

JToken pathResult = jsonObj.SelectToken("results[0].example");

return pathResult.ToString();

A: The problem you are experiencing is that the C# version of JsonPath does not include a Json parser so you have to use it with another Json framework that handles serialization and deserialization.
The way JsonPath works is to use an interface called IJsonPathValueSystem to traverse parsed Json objects.  JsonPath comes with a built-in BasicValueSystem that uses the IDictionary interface to represent Json objects and the IList interface to represent Json arrays.
You can create your own BasicValueSystem-compatible Json objects by constructing them using C# collection initializers but this is not of much use when your Json is coming in in the form of strings from a remote server, for example.
So if only you could take a Json string and parse it into a nested structure of IDictionary objects, IList arrays, and primitive values, you could then use JsonPath to filter it!  As luck would have it, we can use Json.NET which has good serialization and deserialization capabilities to do that part of the job.
Unfortunately, Json.NET does not deserialize Json strings into a format compatible with the BasicValueSystem.  So the first task for using JsonPath with Json.NET is to write a JsonNetValueSystem that implements IJsonPathValueSystem and that understands the JObject objects, JArray arrays, and JValue values that JObject.Parse produces.
So download both JsonPath and Json.NET and put them into a C# project.  Then add this class to that project:
public sealed class JsonNetValueSystem : IJsonPathValueSystem
{
    public bool HasMember(object value, string member)
    {
        if (value is JObject)
                return (value as JObject).Properties().Any(property => property.Name == member);
        if (value is JArray)
        {
            int index = ParseInt(member, -1);
            return index >= 0 && index < (value as JArray).Count;
        }
        return false;
    }

    public object GetMemberValue(object value, string member)
    {
        if (value is JObject)
        {
            var memberValue = (value as JObject)[member];
            return memberValue;
        }
        if (value is JArray)
        {
            int index = ParseInt(member, -1);
            return (value as JArray)[index];
        }
        return null;
    }

    public IEnumerable GetMembers(object value)
    {
        var jobject = value as JObject;
        return jobject.Properties().Select(property => property.Name);
    }

    public bool IsObject(object value)
    {
        return value is JObject;
    }

    public bool IsArray(object value)
    {
        return value is JArray;
    }

    public bool IsPrimitive(object value)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        return value is JObject || value is JArray ? false : true;
    }

    private int ParseInt(string s, int defaultValue)
    {
        int result;
        return int.TryParse(s, out result) ? result : defaultValue;
    }
}

Now with all three of these pieces we can write a sample JsonPath program:
class Program
{
    static void Main(string[] args)
    {
        var input = @"
              { ""store"": {
                    ""book"": [
                      { ""category"": ""reference"",
                            ""author"": ""Nigel Rees"",
                            ""title"": ""Sayings of the Century"",
                            ""price"": 8.95
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""Evelyn Waugh"",
                            ""title"": ""Sword of Honour"",
                            ""price"": 12.99
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""Herman Melville"",
                            ""title"": ""Moby Dick"",
                            ""isbn"": ""0-553-21311-3"",
                            ""price"": 8.99
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""J. R. R. Tolkien"",
                            ""title"": ""The Lord of the Rings"",
                            ""isbn"": ""0-395-19395-8"",
                            ""price"": 22.99
                      }
                    ],
                    ""bicycle"": {
                      ""color"": ""red"",
                      ""price"": 19.95
                    }
              }
            }
        ";
        var json = JObject.Parse(input);
        var context = new JsonPathContext { ValueSystem = new JsonNetValueSystem() };
        var values = context.SelectNodes(json, "$.store.book[*].author").Select(node => node.Value);
        Console.WriteLine(JsonConvert.SerializeObject(values));
        Console.ReadKey();
    }
}

which produces this output:
["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]

This example is based on the Javascript sample at the JsonPath site:

*

*Javascript Usage and Example

A: For those that don't like LINQ (.NET 2.0):
namespace JsonPath
{

    public sealed class JsonNetValueSystem : IJsonPathValueSystem
    {

        public bool HasMember(object value, string member)
        {
            if (value is Newtonsoft.Json.Linq.JObject)
            {
                // return (value as JObject).Properties().Any(property => property.Name == member);

                foreach (Newtonsoft.Json.Linq.JProperty property in (value as Newtonsoft.Json.Linq.JObject).Properties())
                {
                    if (property.Name == member)
                        return true;
                }

                return false;
            }

            if (value is Newtonsoft.Json.Linq.JArray)
            {
                int index = ParseInt(member, -1);
                return index >= 0 && index < (value as Newtonsoft.Json.Linq.JArray).Count;
            }
            return false;
        }

        public object GetMemberValue(object value, string member)
        {
            if (value is Newtonsoft.Json.Linq.JObject)
            {
                var memberValue = (value as Newtonsoft.Json.Linq.JObject)[member];
                return memberValue;
            }
            if (value is Newtonsoft.Json.Linq.JArray)
            {
                int index = ParseInt(member, -1);
                return (value as Newtonsoft.Json.Linq.JArray)[index];
            }
            return null;
        }

        public System.Collections.IEnumerable GetMembers(object value)
        {
            System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();

            var jobject = value as Newtonsoft.Json.Linq.JObject;
            /// return jobject.Properties().Select(property => property.Name);

            foreach (Newtonsoft.Json.Linq.JProperty property in jobject.Properties())
            {
                ls.Add(property.Name);
            }

            return ls;
        }

        public bool IsObject(object value)
        {
            return value is Newtonsoft.Json.Linq.JObject;
        }

        public bool IsArray(object value)
        {
            return value is Newtonsoft.Json.Linq.JArray;
        }

        public bool IsPrimitive(object value)
        {
            if (value == null)
                throw new System.ArgumentNullException("value");

            return value is Newtonsoft.Json.Linq.JObject || value is Newtonsoft.Json.Linq.JArray ? false : true;
        }

        private int ParseInt(string s, int defaultValue)
        {
            int result;
            return int.TryParse(s, out result) ? result : defaultValue;
        }

    }

}

Usage:
object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(input);

JsonPath.JsonPathContext context = new JsonPath.JsonPathContext { ValueSystem = new JsonPath.JsonNetValueSystem() };

foreach (JsonPath.JsonPathNode node in context.SelectNodes(obj, "$.store.book[*].author"))
{
    Console.WriteLine(node.Value);
}

A: I found that the internal JavaScriptSerializer() can work just fine as long as filtering is not required.
Using the dataset and examples from JsonPath Dataset + Examples
My source for the JsonPath implementation was GitHub
public static string SelectFromJson(string inputJsonData, string inputJsonPath)
{
    // Use the serializer to deserialize the JSON but also to create the snippets
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    serializer.MaxJsonLength = Int32.MaxValue;

    dynamic dynJson = serializer.Deserialize<object>(inputJsonData);

    var jsonPath = new JsonPath.JsonPathContext();
    var jsonResults = jsonPath.Select(dynJson, inputJsonPath);

    var valueList = new List<string>();
    foreach (var node in jsonResults)
    {
        if (node is string)
        {
            valueList.Add(node);
        }
        else
        {
            // If the object is too complex then return a list of JSON snippets
            valueList.Add(serializer.Serialize(node));
        }
    }
    return String.Join("\n", valueList);
}

The function is used as follows.
    var result = SelectFromJson(@"
{ ""store"": {
        ""book"": [
            { ""category"": ""fiction"",
                ""author"": ""J. R. R. Tolkien"",
                ""title"": ""The Lord of the Rings"",
                ""isbn"": ""0-395-19395-8"",
                ""price"": 22.99
            }
        ]
    }
}", "$.store.book[*].author");


text:
Q: React Form loses input on reload im having trouble with a project of mine with the useState hook. This is for a declaration of an event.
This component can be opened from a list of all the other declas{ which works fine} and then everything shows however if you reload the page/open it from a link nothing shows up in the following fields even when it does get the decla using using the useEffect hoop(at least it logs it out to the console)
TLDR;
when component called/opened from a list it works and loads all the data but when the page is reloaded it is all lost and doesnt load it again with useState
ive taken the liberty to reduces the amount of data show as it is a pretty long file already.
import { useContext, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Select from "react-select";
import CreatableSelect from "react-select/creatable";
import DeclaContext from "../../context/DeclaContext";
import LedenContext from "../../context/LedenContext";
import EventContext from "../../context/EventContext";

export const DeclaFrom = () => {
  let { id } = useParams();
  const navigate = useNavigate();
  const { user, leden } = useContext(LedenContext);
  const { events } = useContext(EventContext);
  let { declas, GET, GET_decla, POST, PUT, DELETE, boekstuks, POST_boekstuk } =
    useContext(DeclaContext);
  // useEffect(() => {
  //   const get = async () => {
  //     await GET();
  //     const data = await GET_decla(id);
  //     setDecla(data);
  //   };
  //   get();
  //   // eslint-disable-next-line
  // }, [id]);
  console.log(declas?.find((de) => (de.id === id ? true : false)));
  const [decla, setDecla] = useState(declas?.find((de) => de.id === id));
  const [event, setEvent] = useState(decla && decla?.event);
  const [owner, setOwner] = useState(decla ? decla?.owner : user.lid_id);
  const [content, setContent] = useState(decla ? decla?.content : "");
  const [total, setTotal] = useState(decla ? decla?.total : 0);
  const [receipt, setReceipt] = useState(decla && decla?.receipt);
  const [boekstuk, setBoekstuk] = useState(decla ? decla?.boekstuk : "");
  const [content_ficus, setContent_ficus] = useState(
    decla ? decla?.content_ficus : ""
  );
  const optionsLeden = [
    { label: "Select All", value: "all" },
    ...leden?.map((lid) => ({
      value: lid.id,
      label: lid?.initials,
    })),
  ];
  const [defaultValues, setDefaultValues] = useState(
    decla
      ? decla?.present?.map((pres) =>
          optionsLeden?.find((x) => x.value === pres)
        )
      : []
  );
  const optionsBoekstuk = boekstuks?.map((boekstuk) => ({
    value: boekstuk?.id,
    label: boekstuk?.name,
  }));
  const optionsEvents = events?.map((event) => ({
    value: event.id,
    label: event.description + " " + event.start_date,
  }));
  async function createBookstuk(inputValue) {
    const BSid = await POST_boekstuk({ name: inputValue });
    setBoekstuk(optionsBoekstuk?.find((x) => x.id === BSid)?.value);
  }
  const onDelete = (e) => {
    e.preventDefault();
    DELETE({
      id,
    });
    setDeleted(true);
  };
  const onSubmit = (e) => {
    // if (!event | !content | !total | !present) {
    //   alert("Je moet een evenement kiezen");
    //   return;
    // }
    e.preventDefault();
    if (decla) {
      PUT({
        id,
        event,
        content,
        total,
        receipt,
        boekstuk,
      });
      navigate("/declas");
    } else {
      POST({
        event,
        content,
        total,
        receipt,
        boekstuk,
      });
    }
    setDeleted(false);
  };
  return (

        <form>

              {user.roles.includes("Fiscus") && (

                    Lid:

                    <Select
                      defaultValue={optionsLeden?.find(
                        (x) => x.value === owner
                      )}
                      options={optionsLeden?.filter(
                        (x) => !["all", 19900].includes(x.value)
                      )}
                      name="owner"
                      id="id_present"
                      onChange={(e) => {
                        setOwner(e.value);
                      }}
                    />

              )}

                  Event:

                  <Select
                    defaultValue={optionsEvents?.find(
                      (x) => x.value === event?.id
                    )}
                    options={optionsEvents}
                    name="event"
                    onChange={(e) => {
                      setEvent(e.value);
                    }}
                  />

                  Total:

                  <input
                    type="number"
                    onChange={(e) => setTotal(e.target.value)}
                    name="total"
                    value={total}
                    step="any"
                    className="input"
                    required
                    id="id_total"
                  />

                  Present:

                <Select
                  isMulti
                  value={defaultValues}
                  options={optionsLeden}
                  required
                  name="present"
                  id="id_present"
                  onChange={(e) => {
                    if (e.some((val) => val.value === "all")) {
                      setPresent(
                        optionsLeden
                          ?.filter((x) => x.value !== "all")
                          .map((x) => x.value !== "all" && x.value)
                      ); // change the value going to the API

                      setDefaultValues(
                        optionsLeden
                          ?.filter((x) => x.value !== "all")
                          .map((x) => x.value !== "all" && x)
                      ); // change the values displayed
                    } else {
                      setPresent(e?.map((x) => x.value)); // change the value going to the API
                      setDefaultValues(e?.map((x) => x)); // change the values displayed
                    }
                  }}
                />

                  Receipt:

                  <input
                    type="file"
                    name="receipt"
                    required
                    accept="image/*"
                    onChange={(e) => {
                      setReceipt(e.target.files[0]);
                    }}
                    className="input"
                    id="id_receipt"
                  />

                  Boekstuk:

                  <CreatableSelect
                    defaultValue={optionsBoekstuk?.find(
                      (x) => x.value === boekstuk
                    )}
                    options={optionsBoekstuk}
                    name="boekstuk"
                    id="id_boekstuk"
                    onCreateOption={createBookstuk}
                    onChange={(e) => {
                      setBoekstuk(e.value);
                    }}
                  />

                  Content ficus:

                  <textarea
                    onChange={(e) => setContent_ficus(e.target.value)}
                    name="content_ficus"
                    value={content_ficus}
                    cols="40"
                    rows="10"
                    maxLength="100"
                    className="input"
                    id="id_content_ficus"
                  ></textarea>

        </form>

  );
};
export default DeclaFrom;

Thanks for your help

A: I had a similar issue in a recent project. The problem you're facing is that your state is being erased when you reload the page.
In your useEffect hook, remove id from the dependency array (but leave the empty array) so that it will run once on every render. This way when you reload the page useEffect will run your api call and re-populate your state.
useEffect(() => {
    const get = async () => {
      await GET();
      const data = await GET_decla(id);
      setDecla(data);
    };
    get();
   }, []);

veel geluk!

A: useState values will not persist after page reloads: this is a standard behavior of React.  After page reload, all your useState values will reset to their default values.
If you need values to persist after refresh, then you will want to use a browser utility like localStorage.
As an example, this is how I would set/get the value:
const stateFromLocalStorage = localStorage.getItem("itemKey")

const [someState, setSomeState] = useState(stateFromLocalStorage || defaultState)

const settingState = (key, value) => {
  localStorage.setItem(key, value)
  setSomeState(value)
}

I grab the item from localStorage first, and attempt to assign it as the default value of the useState.  If the local storage value doesn't exist, then stateFromLocalStorage will be undefined, and it will set defaultState instead because of the logical || operator.
When setting the state, I set it both with the useState setter function, as well as the local storage setItem function.  That way local storage and component state will stay in sync.


text:
Q: retrieve child object by evaluating grandchildren object in laravel I have 2 models, User and Conversation related to each other with a many-to-many relationship, many users to many conversations.
On my models I have:
User:
public function conversation() {
    return $this->belongsToMany('App\Models\Conversation');
}

Conversation:
public function users() {
    return $this->belongsToMany('App\Models\User');
}

So I could get the conversations a user has by : $user->conversation; and vice versa, retrieve the users a conversation has by $conversation->users, works like a charm. The problem is that I want a way to retrieve all users a certain user has made contact before, in few words, something like:
$user = User::find(1);
$talkedUsers = $user->conversation->user.

And also a way to check all the conversation user 'x' has made with user 'y' ('if any')
$userX = User::find(1);
$userY = 2;

$talkedUser = $userX->conversation->where('user.id', '=', $userY);

Obviously, the code above won't work. I wish to know if something like this is possible to accomplish without adding a complex raw query, I hope is possible only using only QueryBuilder.

A:
The problem is that I want a way to retrieve all users a certain user
has made contact before,

$user->conversation is actually a collection of conversations, it is better to use plural i.e. $user->conversations. Then you can use higher order messages to deal with multiple objects at once. See https://laravel.com/docs/8.x/collections#higher-order-messages for more information
$users = $user->conversations->flatMap->users->unique('id');

flatMap combines multiple User collections retrieved from multiple Conversation objects into one collection of User objects then to remove duplicate users, you can use unique('id')

And also a way to check all the conversation user 'x' has made with
user 'y' ('if any')

First you should query all conversations from x then filter only conversations that have relationships with y.
$userX = User::find($x);

$conversations = $userX->conversations()
    ->whereHas('users', function($query) use ($y) {
        $query->where('users.id', $y);
    })
    ->get();


text:
Q: Why are transmission lines and waveguides needed for high frequency? At low frequency, we can just use a piece of wire to connect electrical components, but why are special transmission lines and waveguides needed for high frequency circuits?
Also I am confused by the usages of waveguides in a circuit. In a RF circuit, is it a current that flows through waveguides or is it electromagnetic wave that flow through waveguides? If it's a current, why do we call it a waveguide?

A:
At low frequency, we can just use a piece of wire to connect electrical components, but why are special transmission lines and waveguides needed for high frequency circuits?

Transmission lines are not needed in the sense that it's absolutely impossible without them, but it would be very very difficult to design and debug something that didn't use them, once the dimensions of the circuit are bigger than roughly λ/10 at the operating frequency.
Once you are above that soft limit, any time the impedance of part of the circuit differs from the impedance of the previous part, you get a reflection which significantly affects the operation of the circuit. You still get reflections below that limit, but they don't affect behaviour significantly.
If instead you make everything matched to a common impedance (two frequently used standards are 50 and 75 ohms), reflections at junctions are minimal, and you can simply cascade matched blocks and expect them to work. For instance, it doesn't matter if you use a 1 m or a 2.5 m long 50 ohm cable to your 50 ohm spectrum analyser, it still behaves the same way. If OTOH you had a 75 ohm cable, or worse still a piece of open wire, you would still get some sort of reading, but the amplitude would be dependent on the exact frequency and length of wire, a nightmare to design or debug with, basically impossible to use easily.

Also I am confused by the usages of waveguides in a circuit. In a RF circuit, is it a current that flows through waveguides or is it electromagnetic wave that flow through waveguides? If it's a current, why do we call it a waveguide?

In an RF circuit, an electromagnetic wave propagates along the waveguide. In coaxial cable, we tend to think of this as a voltage wave across the conductors, and a current wave along the conductors, with a voltage/current ratio equal to the characteristic impedance of the line. In a hollow waveguide, you can consider it as a plane electromagnetic wave zigzagging along the guide, bouncing off the walls, as a result of which a current flows in the walls, and patches of charge appear on the walls.
We call it a waveguide, because the electromagnetic wave is guided by the conductors, as opposed to being a 'free space' wave that propagates out from an antenna.

When I think of a circuit, I always think a current flowing through the circuit. But in RF, EM wave propagation is always talked about.

When we talk about circuits, and in fact things in general in physics, we try to use the simplest model that captures everything important. In low frequency circuits, just as in high frequency ones, energy is transported by electromagnetic waves (and underneath EM waves there's something going on with photons and relativity that does my head in). However, in low frequency circuits, we can make a simplifying abstraction to just current and voltage, so we do, because it's good enough. In high frequency circuits, it's no longer a good enough approximation, so we have to worry about the waves.

A: Basically, it has to do with the Maxwell equations and energy transport. The two important equations for this are:
$$\text{curl}\,\vec{E} = -\frac{\partial\vec{B}}{\partial t} \qquad \text{and}\qquad \text{curl}\,\vec{H}=\vec{J}+\frac{\partial\vec{D}}{\partial t}$$
This means that an electric field creates a magnetic one and vice versa. If a harmonic current density \$\vec{J}\$ is impressed, a harmonically changing magnetic field is created. This magnetic field in turn creates a harmonic electric field, which then generates a magnetic field itself. And now you're back to the beginning. Magnetic field -> electric field -> magnetic field -> ... and so on. The way in which the fields are directed towards each other creates a wave that propagates away from the cause (current density).
This image shows the wave propagation (but keep in mind that only one specific direction is shown):

This does not matter that much at low frequencies, because the derivatives quickly become very small. Derivation means multiplication by \$\text{j}\omega\$, which is why it works better at higher frequencies. But what are high frequencies? What is really important is the dimension in relation to the wavelength. Energy providers, for example, have to take into account certain transmission line effects even at 60 Hz, because distances of several hundred kilometers are covered here in some cases.
But back to the piece of wire (which behaves as an antenna). If you want to direct the electromagnetic wave and thus the energy in one specific direction, special structures are necessary. These structures are transmission lines and waveguides. Waveguides are so named because they guide an (original free space) wave along one direction.


text:
Q: MySQL Where condition groupings from remote table I have a products table referencing a products 'filter' table - this table contains such things as color, size, condition etc (attributes).
How do I go about building a query to show results from searches?
SELECT DISTINCT shop_products.*
FROM shop_products
JOIN shop_products_filters ON
 (shop_products.id = shop_products_filters.product_id)
WHERE category_id = '2' AND price >= '1.00' AND price <= '10.00'
AND (filter_category_id = '161' AND filter_option_id IN (1046,1051))
AND (filter_category_id = '162' AND filter_option_id IN (1057,1058))
ORDER BY price ASC

Above is an example of my code that is not working.
Filter Category ID 161 = Color
Filter Category ID 162 = Size
Filter Option ID 1046 + 1051 are black,red etc
Filter Option ID 1057 + 1058 are small, medium etc
I know the SQL above won't work because filter_category_id cannot be both 161 and 162 - I'm pretty sure I'm missing a join of here somewhere - to check the filter options exist in the shop_products_filters table first.
Hope that makes sense

A: You can use EXISTS to check if that condition is met in another table:
SELECT DISTINCT shop_products.*
FROM shop_products
JOIN shop_products_filters ON
 (shop_products.id = shop_products_filters.product_id)
WHERE category_id = '2' AND price >= '1.00' AND price <= '10.00'
AND EXISTS( SELECT 1 FROM shop_products_filters WHERE filter_category_id = '161' AND filter_option_id IN (1046,1051))
AND EXISTS( SELECT 1 FROM shop_products_filters WHERE filter_category_id = '162' AND filter_option_id IN (1057,1058))
ORDER BY price ASC


text:
Q: System of Schrodinger equations I know that Schrodinger equation for 1 dimension is given by:
$-u''+qu=\lambda u$ and if I want to work on a system for say 2 dimensions,
the system would be:
\begin{equation}
\left(\begin{array}{c} -u_1''\\ -u_2'' \end{array}\right)
+\left(\begin{array}{cc} q_1 & q_2\\ q_3 & q_4\end{array}\right)
\left(\begin{array}{c} u_1 \\ u_2 \end{array}\right)
=\lambda \left(\begin{array}{c} u_1 \\ u_2 \end{array}\right)
\end{equation}
My question is: is this system right and does make sense? and if the q in 1 dimension is periodic can I make the matrix $Q$ in this system:
\begin{equation}
Q=\left(\begin{array}{cc} q_1 & q_2\\ q_3 & q_4\end{array}\right)
\end{equation}
to be periodic?
If this system I made is correct, is there any examples for this case of system in quantum mechanics or other field of applications?


text:
Q: Suppose $G$ is a group and $N$ is a normal subgroup of $G$. Prove the following:
*

*$(Nx)(Ny)=Nxy$

*$N(x)(Nx^{-1})=(Nx^{-1})(Nx)=N$

*$N(Nx)=(Nx)N=Nx$

Deduce that the right cosets of $N$ in $G$ form a group under the given multiplication.

A: Something which I like to do  is using the monoid of nonempty subsets of $G$. Let $A,B\subset G$, we will define $AB=\{ab|a\in A,b\in B\}$. It is easy to show that multiplication of sets is associative. Note that the cosets $Nx,xN$ are $N\{x\},\{x\}N$ respectively. Also note that for any subgroup of $H$ of $G$ we have $HH=H$
In the next proof I will use the facts :$NN=N$ ,$N\{x\}=\{x\}N$ and the fact that multiplication of subsets is associative.
a) $(N\{x\})(N\{y\})=N(\{x\}N\{y\})=N(N\{x\}\{y\})=NN(\{x\}\{y\})=N\{xy\}$
b),c) can be proved similarly.


text:
Q: Why does ion-input display a second 1-pixel-wide text field? In the signin page of my ionic 2 app, I have the following:
<form [formGroup]="signinForm" (submit)="onSubmit($event)" style="padding-top: 20px;">

            <ion-input #username type="text" placeholder="Username" formControlName="username" autocapitalize="off"></ion-input>

</form>

This produces a weird 1-pixel-wide artifact.
Here is what it produces on the page:

    <ion-input formcontrolname="agencyNumber" placeholder="Agency ID" type="text" class="input input-md ng-untouched ng-pristine ng-valid" ng-reflect-name="agencyNumber" ng-reflect-placeholder="Agency ID" ng-reflect-type="text">
        <input class="text-input ng-untouched ng-pristine ng-valid text-input-md" formcontrolname="agencyNumber" placeholder="Agency ID" autocomplete="off" autocorrect="off" ng-reflect-klass="text-input" ng-reflect-ng-class="text-input-md" ng-reflect-model="test9994" ng-reflect-type="text" type="text" ng-reflect-placeholder="Agency ID">

        <input aria-hidden="true" next-input="" ng-reflect-type="text" type="text">
        <button class="text-input-clear-icon disable-hover button button-md button-clear button-clear-md" clear="" ion-button="" type="button" ng-reflect-hidden="true" hidden="">

        </button>

   </ion-input>

That weird little artifact appears to be the second input field:
<input aria-hidden="true" next-input="" ng-reflect-type="text" type="text">

What is this? Why is it appearing?
EDIT: I have updated to ionic 2.0.0 with latest supported dependencies, and the problem persists.

A: I believe thats from a validator from your FormBuilder. It is supposed to  turn red and underline the field if you fill it out and happens to be invalid. You should be able to remove it by editing the ng-valid and ng-invalid classes and making


text:
Q: Scheduled task agent wp7 soap client does not work I have this:
public class ScheduledAgent : ScheduledTaskAgent
{
    ...

    protected override void OnInvoke(ScheduledTask task)
    {
        var userSettings = Utils.LoadSettings();
        try
        {
            var client = new CheckinServiceSoapClient();
            var token = WsApiCaller.Token;
            var point = ... // User Location;
            if (point != null)
            {
                client.UserTrackAsync(token, userSettings.UserId,
                    point.Latitude, point.Longitude,
                    point.Position.Location.HorizontalAccuracy,
                    point.Position.Location.Altitude,
                    point.Position.Location.Speed,
                    point.Position.Location.VerticalAccuracy,
                    point.Position.Location.Course,
                    "BACKGROUND_AGENT");
            }
        }
        catch
        {
        }
        NotifyComplete();
    }
}

OnInvoke event occurs. But call of UserTrackAsync is not executing.

A: Your client.UserTrackAsync is an async call. The problem is that NotifyComplete(); is executed before client.UserTrackAsync has a chance to finish.
You need to call it in the UserTrackCompleted handler (and delete it from the original place):
client.UserTrackCompleted += (sender, args) =>
{
    var res = args.Result.Retval;
    NotifyComplete();
};