Q: Spring boot with data jpa getting error on startup Getting an error while starting my Spring boot application. Here is a stack trace but I am unable to find the root cause. I am using spring boot 2.3.4 with spring data jpa. Any help appreciated.
{"timestamp": "12/21/2020 18:52:02:0871", "class": "org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator", "file": "JtaPlatformInitiator.java", "level" : " INFO", "line_number" : "52", "url": "", "ip_address": "", "server_trace_id":"", "message": HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform], "method": "initiateService", "thread_name": "task-1"},
{"timestamp": "12/21/2020 18:52:02:0872", "class": "org.hibernate.query.spi.NamedQueryRepository", "file": "NamedQueryRepository.java", "level" : "DEBUG", "line_number" : "151", "url": "", "ip_address": "", "server_trace_id":"", "message": Checking 0 named HQL queries, "method": "checkNamedQueries", "thread_name": "task-1"},
{"timestamp": "12/21/2020 18:52:02:0872", "class": "org.hibernate.query.spi.NamedQueryRepository", "file": "NamedQueryRepository.java", "level" : "DEBUG", "line_number" : "167", "url": "", "ip_address": "", "server_trace_id":"", "message": Checking 0 named SQL queries, "method": "checkNamedQueries", "thread_name": "task-1"},
{"timestamp": "12/21/2020 18:52:02:0891", "class": "org.hibernate.internal.SessionFactoryRegistry", "file": "SessionFactoryRegistry.java", "level" : "DEBUG", "line_number" : "52", "url": "", "ip_address": "", "server_trace_id":"", "message": Initializing SessionFactoryRegistry : org.hibernate.internal.SessionFactoryRegistry@263b5690, "method": "<init>", "thread_name": "task-1"},
{"timestamp": "12/21/2020 18:52:02:0891", "class": "org.hibernate.internal.SessionFactoryRegistry", "file": "SessionFactoryRegistry.java", "level" : "DEBUG", "line_number" : "74", "url": "", "ip_address": "", "server_trace_id":"", "message": Registering SessionFactory: 64cd8993-8947-4c28-8a99-8717be785280 (<unnamed>), "method": "addSessionFactory", "thread_name": "task-1"},
{"timestamp": "12/21/2020 18:52:02:0891", "class": "org.hibernate.internal.SessionFactoryRegistry", "file": "SessionFactoryRegistry.java", "level" : "DEBUG", "line_number" : "81", "url": "", "ip_address": "", "server_trace_id":"", "message": Not binding SessionFactory to JNDI, no JNDI name configured, "method": "addSessionFactory", "thread_name": "task-1"},
{"timestamp": "12/21/2020 18:52:02:0896", "class": "org.hibernate.internal.SessionFactoryImpl", "file": "SessionFactoryImpl.java", "level" : "DEBUG", "line_number" : "771", "url": "", "ip_address": "", "server_trace_id":"", "message": HHH000031: Closing, "method": "close", "thread_name": "restartedMain"},
{"timestamp": "12/21/2020 18:52:02:0897", "class": "org.hibernate.type.spi.TypeConfiguration$Scope", "file": "TypeConfiguration.java", "level" : "DEBUG", "line_number" : "350", "url": "", "ip_address": "", "server_trace_id":"", "message": Un-scoping TypeConfiguration [org.hibernate.type.spi.TypeConfiguration$Scope@3fbaa2e9] from SessionFactory [org.hibernate.internal.SessionFactoryImpl@1741883a], "method": "unsetSessionFactory", "thread_name": "restartedMain"},
{"timestamp": "12/21/2020 18:52:02:0902", "class": "org.hibernate.service.internal.AbstractServiceRegistryImpl", "file": "AbstractServiceRegistryImpl.java", "level" : "DEBUG", "line_number" : "419", "url": "", "ip_address": "", "server_trace_id":"", "message": Implicitly destroying ServiceRegistry on de-registration of all child ServiceRegistries, "method": "deRegisterChild", "thread_name": "restartedMain"},
{"timestamp": "12/21/2020 18:52:02:0902", "class": "org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl", "file": "BootstrapServiceRegistryImpl.java", "level" : "DEBUG", "line_number" : "295", "url": "", "ip_address": "", "server_trace_id":"", "message": Implicitly destroying Boot-strap registry on de-registration of all child ServiceRegistries, "method": "deRegisterChild", "thread_name": "restartedMain"},
Exception in thread "task-2" org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'delegatingApplicationListener': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220)
DefaultSingletonBeanRegistry.java:220
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
AbstractBeanFactory.java:322
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
AbstractBeanFactory.java:207
    at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245)
AbstractApplicationEventMulticaster.java:245
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197)
AbstractApplicationEventMulticaster.java:197
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134)
SimpleApplicationEventMulticaster.java:134
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404)
AbstractApplicationContext.java:404
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361)
AbstractApplicationContext.java:361
    at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:99)
DataSourceInitializedPublisher.java:99
    at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.access$100(DataSourceInitializedPublisher.java:50)
DataSourceInitializedPublisher.java:50
    at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher$DataSourceSchemaCreatedPublisher.lambda$postProcessEntityManagerFactory$0(DataSourceInitializedPublisher.java:200)
DataSourceInitializedPublisher.java:200
{"timestamp": "12/21/2020 18:52:02:0905", "class": "com.zaxxer.hikari.HikariDataSource", "file": "HikariDataSource.java", "level" : " INFO", "line_number" : "350", "url": "", "ip_address": "", "server_trace_id":"", "message": HikariPool-1 - Shutdown initiated..., "method": "close", "thread_name": "restartedMain"},
{"timestamp": "12/21/2020 18:52:02:0906", "class": "com.zaxxer.hikari.pool.HikariPool", "file": "HikariPool.java", "level" : "DEBUG", "line_number" : "421", "url": "", "ip_address": "", "server_trace_id":"", "message": HikariPool-1 - Before shutdown stats (total=1, active=0, idle=1, waiting=0), "method": "logPoolState", "thread_name": "restartedMain"},
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at java.base/java.lang.Thread.run(Thread.java:832)

A: Set the JAVA_HOME path and update JDK version. After that restart your server and it should work just fine!
If this doesn't work, check how many instances of tomcat you have. If you have more than one, shut them down.
It can also be a problem with the @Transactional annotation if you're using it wrong, you can see more details here- >http://www.javablog.fr/spring-transaction-visibility-proxy-propagation-required-and-requires_new.html


Q: How to manage automation via ampscript API - second part I would like to close the discussion thread on this related topic Manage automation via ampscript API. If you have additional information to complement it would be great to hear on the answers!
Here is my take, in case you would like to trigger an Automation via AMPSCript, or i.e. directly on the exclusion script from JB, or via CloudPage, you can follow the below instructions.
After some rounds of testing, I was able to fully confirm that ProgramID property throws 500 CP errors, therefore ObjectID is the property needed to invoke the InvokePerform function for the Automation Object.
%%[
set @obj = CreateObject("Automation")
SetObjectProperty(@obj, "ObjectID", "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx")
Set @performStatusCode = InvokePerform(@obj, "start", @performStatusMessage)
]%%
performStatusCode: %%=v(@performStatusCode)=%%
performStatusMessage: %%=v(@performStatusMessage)=%%

If you need to retrieve the ObjectID quickly, you can use the network in the developer console as per the attached screenshot below.

In case you would like to retrieve the ObjectID directly from AMPScript, you can use some filtering by the Automation name or CustomerKey.
  %%[

var @rr, @ObjectID, @queryDefinitions
set @rr = CreateObject("RetrieveRequest")
SetObjectProperty(@rr, "ObjectType", "Automation")
AddObjectArrayItem(@rr, "Properties", "Name")
AddObjectArrayItem(@rr, "Properties", "ProgramID")

set @sfp = CreateObject("SimpleFilterPart")
SetObjectProperty(@sfp, "Property", "Name")
SetObjectProperty(@sfp, "SimpleOperator", "equals")
AddObjectArrayItem(@sfp, "Value", "test-SSJS-assets")

SetObjectProperty(@rr,"Filter", @sfp)

set @queryDefinitions = InvokeRetrieve(@rr, @rrStatus, @rrRequestID)

output(concat("rrStatus: ", @rrStatus))
output(concat("<br>rrRequestID: ", @rrRequestID))

if rowcount(@queryDefinitions) > 0 then

  var @queryDefinition, @ObjectID, @obj

  set @queryDefinition = Row(@queryDefinitions, 1)
  set @ObjectID = Field(@queryDefinition, "ObjectID")

  set @obj = CreateObject("Automation")

  SetObjectProperty(@obj, "ObjectID", @ObjectID)
  Set @performStatusCode = InvokePerform(@obj, "start", @performStatusMessage)

endif

]%%

As per the below screenshot of the outcome, rendering the variables provides me an overall idea if the code was executed properly.

End note: Please make sure the Automation is in an active state.


Q: Does C# compiler convert and store static variables? My program uses the code:
Convert.ToDouble(Int32.MaxValue)

Fairly regularly. I was just curious about how this is handled by the compiler. Is it stored as a static double or is it executed in run time?

A: The constant Int32.MaxValue is stored at compile time, and in fact your code would be converted to Convert.ToDouble(0x7FFFFFFF) at compile time. The equivalent IL is:
ldc.i4      FF FF FF 7F
call        System.Convert.ToDouble

This value is also saved so it can be retrieved at run-time through reflection.
However, Convert.ToDouble is a function that is only evaluated at run-time.
As minitech suggests, (double)Int32.MaxValue is evaluated at compile-time. The equivalent IL is:
ldc.r8      00 00 C0 FF FF FF DF 41


Q: Parse string using C# LINQ Need help in parse string using C# LINQ
I have a string like this
11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2

I would like to split this string on 448= then take an array start getting line "starts with 448" get the last string in the line which is 452=
I'm trying this logic using LINQ to get the final output but it's not working.
var parties = rptstr.Split(new string[] { "453=" }, StringSplitOptions.None).Select(p => p.Split(new string[] {"448="},StringSplitOptions.None);

 var str448 = (from lnprty in parties
                                   where lnprty.ToString().StartsWith("448=")
                                    //let tmp = line1.ToString()
                                   select new PartyRoleModel()
                                     {
                                         companyid == lnprty.Where(s => s.EndsWith("452=63,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault(),
                     userid == lnprty.Where(s => s.EndsWith("452=11,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault()
                     companyname == lnprty.Where(s => s.EndsWith("452=13,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault()
                     PhyFlag == lnprty.Where(s => s.EndsWith("452=54,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault()
                                     })
                                .ToList();

I can split the line by 448 but 448 lines comes without 448= since it got split, I need split string also in the line so I can identify the line.
Pls. remember the last line comes with other strings at end (448=W,447=D,452=54,77=O,555=2).
I should get the final output like where 452=63 get companyid(which is in 447=), 452=11 get userid, 452=13 get companyname
Thanks in advance.

A: Try following :
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            Dictionary<int, Dictionary<string, int>> dict = new Dictionary<int, Dictionary<string, int>>();

            StreamReader reader = new StreamReader(FILENAME);
            string input = "";
            while ((input = reader.ReadLine()) != null)
            {

                //string input = "11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2";
                List<string> strArray = input.Split(new char[] { ',' }).ToList();

                //or dictionary
                Dictionary<string, int> rowDict = strArray.Select(x => x.Split(new char[] { '=' })).GroupBy(x => x.Last(), y => int.Parse(y.First())).ToDictionary(x => x.Key, y => y.FirstOrDefault());

                int id = rowDict["CompanyID"];

                dict.Add(id, rowDict);
            }

        }


Q: How to time openGL animations on iPhone? I wonder if there is a time function in apples SDK that is guaranteed to be monotonically increasing? I heard about [NSDate timeIntervalSinceReferenceDate] (which isn't accurate) and the c function mach_absolute_time.
How do all these people timing their animations in openGL ES (is there a frame independent solution)?

A: See this question: How can I get a precise time, for example in milliseconds in objective-c?

A: I use CADisplayLink to timing my animation. When you create a new opengl-es project on xCode, it will give you an sample opengl-es codes, and it control animation by CADisplayLink.
EDIT:
I found I misunderstand this problem.
   I check the CFAbsoluteTimeGetCurrent() method on this apple on-line doc, and it said the method may be not monotonically increasing. And the method CACurrentMediaTime() which I prefered derived value by mach_absolute_time(). The document about CACurrentMediaTime() is on this link.

A: For frame-rate-independent time, I generally use the CFAbsoluteTimeGetCurrent() function. It returns a CFAbsoluteTime (which I believe is typedef'd to double) since some date arbitrarily far in the past.


Q: WebPage font changing while opening in UIWebView within my app My Application is using custom font ("Roboto"), I am opening a HTML page( this web page is also using Roboto font in CSS) in UIWebView within application, in which font of web page is bold.
can anyone help?, what could be the problem.

A: You have following solution may be any one help you.
1) Add in .css and meta tags as follow.
html {
    -webkit-text-size-adjust: none; /* Never autoresize text */
}

and meta tags as follow
<meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0;'>

2) You can also inject both into an existing website, using this javascript code as follow.
var style = document.createElement(\"style\");
document.head.appendChild(style);
style.innerHTML = "html{-webkit-text-size-adjust: none;}";
var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);

and Use UIWebViewDelegate (webViewDidFinishLoad) method
- (void)webViewDidFinishLoad:(UIWebView *)webView{

    NSString *javascript = @"var style = document.createElement(\"style\"); document.head.appendChild(style); style.innerHTML = \"html{-webkit-text-size-adjust: none;}\";var viewPortTag=document.createElement('meta');viewPortTag.id=\"viewport\";viewPortTag.name = \"viewport\";viewPortTag.content = \"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\";document.getElementsByTagName('head')[0].appendChild(viewPortTag);";
    [webView stringByEvaluatingJavaScriptFromString:javascript];

}

A: you can implement webView delegate and change font when load webView.
func webViewDidStartLoad(webView : UIWebView) {
    //your code
}


Q: How to make the if condition contain more than one condition? i.e.: if (number % 3 == 0) & (number % 5 == 0): Starting_Num = int(input('Please enter intial number: '))

Ending_Num = int(input('Please enter ending number: '))

for number in range(Starting_Num, (Ending_Num+1)):

    if (number % 3 == 0):
        print(number, '--',  3)
    elif (number % 5 == 0):
        print(number, '--', 5)
    elif (number % 3 == 0) & (number % 5 == 0):
        print(number, '-- both')
    elif (number % 3 != 0) & (number % 5 != 0):
        print(number)

A: you can simply do
if (number % 3 == 0) and (number % 5 == 0):
    your code here...

A: With the Python syntax, you need to use an and instead of &.

Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True")

Source: https://www.w3schools.com/python/python_conditions.asp#:~:text=The%20and%20keyword%20is%20a%20logical%20operator%2C%20and%20is%20used%20to%20combine%20conditional%20statements

A: Does your program error at all? Python 3 allows keyword & as well as and to be used as "and" conditional statements. It should work either way...

A: You can use "and" or "or" operator, difference between them is that "and" should call True if all of the condition are True, "or" - if one of it is True.
example:
a = 1
b = 2
c = 'd'
if type(a) == int and type(b) == int:
   # that will be printed
   print("a, b are numbers")
if type(a) == int and type(c) == int:
   # that will not be printed
   print("a, c are numbers")
if type(a) == int or type(c) == int:
   # that will be printed
   print("a or c is number")

your code should look like:
Starting_Num = int(input('Please enter intial number: '))

Ending_Num = int(input('Please enter ending number: '))

for number in range(Starting_Num, (Ending_Num+1)):

    if (number % 3 == 0):
        print(number, '--',  3)
    elif (number % 5 == 0):
        print(number, '--', 5)
    elif (number % 3 == 0) and (number % 5 == 0):
        print(number, '-- both')
    elif (number % 3 != 0) and (number % 5 != 0):
        print(number)

A: The problem is where you position your 'and' condition. In your code, assuming the input fits the condition (e.g. the number is 15) what will happen is that you will enter the first condition: (if (number % 3 != 0):) and skip all the others, because you used [if / elif] statements. What you need to do is move the condition [elif (number % 3 != 0) & (number % 5 != 0):] to be the first condition, which will ensure that in case the number is divisible by both 3 and 5 - you will first check for both conditions.
Also, in case of logical and use the and operator.
It should look something like this:
Starting_Num = int(input('Please enter intial number: '))

Ending_Num = int(input('Please enter ending number: '))

for number in range(Starting_Num, (Ending_Num+1)):

if (number % 3 == 0) and (number % 5 == 0):
    print(number, '-- both')
elif (number % 3 == 0):
    print(number, '--',  3)
elif (number % 5 == 0):
    print(number, '--', 5)
else:
    print(number)


Q: Xfce4 and Ubuntu 16.04 and recent firefox: get Emacs key bindings How can I get Emacs key bindings in firefox (and other applications) when using Xfce4. Several answers relating to dconf-editor and gconf-editor don't work.

A: On https://forum.xfce.org/viewtopic.php?id=8189 I found the crucial hint: Open xfce4-settings-editor, click on xsettings, click on Gtk and then either change the setting KeyThemeName to Emacs or create the setting KeyThemeName with the New button.
Worked for me without restart or logout/login.


Q: Streaming from obs to Nginx I'm trying to stream from obs to nginx server. I'm using videojs as a player. In OBS Settings I'm using custom Streaming server and the url is  rtmp://localhost/live. this is the configuration file for nginx:
rtmp {
        server {
                listen 1935;
                chunk_size 4096;

                application live {
                        live on;
                        record off;
                }
        }
}

and this is the html part:
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls autoplay preload="none">
    <source src="rtmp://localhost/live" type="rtmp/mp4" />
</video>

A: https://github.com/DigiSkyOps/knife
this is a obs stream server
nginx/config
    rtmp {
  server {
    listen 1935;
    chunk_size 4000;
    application live {
      live on;
    }
    application hls {
        live on;
        hls on;
        hls_path /data/hls;
        hls_fragment 5s;
        hls_playlist_length 10s;
        hls_continuous on;
        hls_cleanup on;
        hls_nested on;
      }
    }
  }


Q: Saving FB access token from FB JS SDK to DB I am implementing 'Login with FB' for my web app using FB JS SDK. I have got the user to return the  access token in the response inside the statusChangeCallback function. However, I am not sure about the best method to store this info to a DB for later use (getting data from graph api). How can the access token and other user info be saved into a DB?
In an attempt to post this data on an API, I have tried to serve this html using an express app but the facebook login popup shows blank where it should say "continue as such and such.."
Should there be a separate API that I should post this data to?
Any clue is appreciated!

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>

  function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
    console.log('statusChangeCallback');
    console.log(response);                   // The current login status of the person.
    if (response.status === 'connected') {   // Logged into your webpage and Facebook.
      testAPI();
    } else {                                 // Not logged into your webpage or we are unable to tell.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this webpage.';
    }
  }

  function checkLoginState() {               // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) {   // See the onlogin handler
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId      : '{app-id}',
      cookie     : true,                     // Enable cookies to allow the server to access the session.
      xfbml      : true,                     // Parse social plugins on this webpage.
      version    : '{api-version}'           // Use this Graph API version for this call.
    });

    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
      statusChangeCallback(response);        // Returns the login status.
    });
  };

  function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }

</script>

<!-- The JS SDK Login Button -->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
</body>
</html>

This code is taken from facebook docs: https://developers.facebook.com/docs/facebook-login/web#example


Q: Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED) (Redis::CannotConnectError) I try to connect to reddis On c9.io
But get this error
/usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:344:in `rescue in establish_connection': Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED) (Redis::CannotConnectError)
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:329:in `establish_connection'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:99:in `block in connect'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:291:in `with_reconnect'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:98:in `connect'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:363:in `ensure_connected'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:219:in `block in process'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:304:in `logging'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:218:in `process'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis/client.rb:118:in `call'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:1330:in `block in sadd'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:45:in `block in synchronize'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:45:in `synchronize'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-4.0.1/lib/redis.rb:1329:in `sadd'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:442:in `call_with_namespace'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:328:in `method_missing'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-1.27.4/lib/resque/data_store.rb:59:in `method_missing'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:94:in `set_schedule'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:51:in `block in schedule='
        from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:50:in `each'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/resque-scheduler-4.3.1/lib/resque/scheduler/scheduling_extensions.rb:50:in `schedule='
        from /home/ubuntu/workspace/UnicumParser/config/initializers/resque.rb:4:in `<top (required)>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `block in load'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:648:in `block in load_config_initializer'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/activesupport-5.0.1/lib/active_support/notifications.rb:166:in `instrument'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:647:in `load_config_initializer'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:611:in `each'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/engine.rb:611:in `block in <class:Engine>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `instance_exec'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `run'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:44:in `each'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:44:in `tsort_each_child'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:415:in `call'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:415:in `each_strongly_connected_component_from'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `each'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `call'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each'
        from /usr/local/rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/initializable.rb:54:in `run_initializers'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/application.rb:352:in `initialize!'
        from /home/ubuntu/workspace/UnicumParser/config/environment.rb:5:in `<top (required)>'
        from /home/ubuntu/workspace/UnicumParser/config.ru:3:in `require_relative'
        from /home/ubuntu/workspace/UnicumParser/config.ru:3:in `block in <main>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:55:in `instance_eval'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:55:in `initialize'
        from /home/ubuntu/workspace/UnicumParser/config.ru:in `new'
        from /home/ubuntu/workspace/UnicumParser/config.ru:in `<main>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:49:in `eval'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:49:in `new_from_string'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/builder.rb:40:in `parse_file'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/server.rb:319:in `build_app_and_options_from_config'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/server.rb:219:in `app'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/server.rb:59:in `app'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/rack-2.0.3/lib/rack/server.rb:354:in `wrapped_app'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/server.rb:124:in `log_to_stdout'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/server.rb:77:in `start'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:90:in `block in server'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
        from /home/ubuntu/workspace/UnicumParser/bin/rails:9:in `require'
        from /home/ubuntu/workspace/UnicumParser/bin/rails:9:in `<top (required)>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `load'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `call'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client/command.rb:7:in `call'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/client.rb:30:in `run'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/bin/spring:49:in `<top (required)>'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `load'
        from /usr/local/rvm/gems/ruby-2.4.0/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `<top (required)>'
        from /home/ubuntu/workspace/UnicumParser/bin/spring:14:in `require'
        from /home/ubuntu/workspace/UnicumParser/bin/spring:14:in `<top (required)>'
        from bin/rails:3:in `load'
        from bin/rails:3:in `<main>'

resque.rb file:
require 'resque'
require 'resque/scheduler'

Resque.schedule = YAML.load_file(File.join(Rails.root, 'config/resque_schedule.yml'))
Resque.logger = Logger.new(Rails.root.join('log', "#{Rails.env}_resque.log"))
Resque.logger.level = Logger::INFO

rails_env = ENV['RAILS_ENV'] || 'development'
Resque.redis.namespace = "resque:#{rails_env}"


Q: Unable to distinguish four cosines from a FFT I have four cosines with frequencies 400e-3, 500e-3, 600e-3 and 700e-3 and I am trying to do the FFT of them but under the time I need, I cannot distinguish the four. Is there a way to distinguish the peaks without changing the tmax time of 1.76 and the frequencies?
import numpy as np
import scipy.fftpack
from scipy.fftpack import fftfreq
from scipy.fft import fft
import matplotlib.pyplot as plt

t = np.linspace(0,1.76,2400)
f = [400e-3, 500e-3, 600e-3, 700e-3] # these are the frequencies
yy = 0

for i in f:
    y = 0.5*np.cos(2*np.pi*i*t)
    yy = yy + y

plt.figure(0)
plt.plot(t, yy)

f = fftfreq(len(t), np.diff(t)[0])
yf = fft(yy)
plt.figure(1)
plt.plot(f[:t.size//2], np.abs(yf[:t.size//2]))
plt.show()

Here are the results:

A: The solution was to increase tmax of
t = np.linspace(0,1.76,2400)

i.e. 1.76. FFT makes bins the size of 1/tmax and the small tmax is, the bigger the bins are leading to less resolution.


Q: Style acronyms long forms and avoid description fields for those that don't have it defined I'm working with the glossaries package, and wanted to modify the long-short style of the glossary like this (edited, it didn't came from a .tex compilation):

For acronyms only (as the real document I'm working on needs to contain both acronyms and normal terms into a single glossary):

*

*Don't put any description if it doesn't have that tag defined in the optional argument, and put the short form of the acronym in bold, a line, and the long form in plain format, all of these in the same line (i.e. avoid any space for the description field).

*Otherwise, put the long form first, then the short form between parentheses, and the given description below (as in the long-short glossary style).

The following MWE shows what I've got so far:
\documentclass[12pt]{article}

\usepackage[xindy]{glossaries}
\usepackage{ifthen}

\makeglossaries

% Style the acronyms
\setacronymstyle{long-short}
\renewcommand*{\acronymsort}[2]{#1} % Order by short form
\renewcommand*{\acronymentry}[1]{%
  \ifthenelse{\equal{\glsentrydesc{#1}}{\glsentrylong{#1}}}{%
    \acronymfont{\glsentryshort{#1} --- \glsentrylong{#1}}%
  }{%
    \acronymfont{\glsentrylong{#1} (\glsentryshort{#1})}%
  }%
}

\newacronym{one}{one}{The number one}
\newacronym{two}{two}{The number two}
\newacronym[description={Just a number with a meaningful description}]{three}{three}{The number three}

\begin{document}
  The numbers \acrshort{one}, \acrshort{two} and \acrshort{three}...
  \setglossarystyle{altlisthypergroup}
  \printglossary[type=main]
\end{document}

*

*The glossary now shows both glossary terms and acronyms (as I'm not using the acronym option for the package).

*For acronyms, I managed to style the acronym long and short forms, according to the value of the description field (the documentation for the package states that the long-short style "copies" the acronym long form into the description field if the user didn't define it).

And the output of compiling the given code is:

Is there a way to:

*

*avoid the description field for the acronyms that don't have it user-defined?

*change the long form for these acronyms to plain format?

Any help will be much appreciated :)

A: I think you might be better off using the glossaries-extra extension package, which allows different abbreviation styles. This package internally loads glossaries, but there are some subtle differences. In particular it uses a completely different abbreviation mechanism. Each entry now has an associated category (set with the category key) and the abbreviation style is set for a particular category using:
\setabbreviationstyle[category-label]{style-name}

where category-label is the category label and style-name is the style. Abbreviations are then defined using \newabbreviation. This has the same syntax as \newacronym. To make it easier to transfer documents over from just the base glossaries package to glossaries-extra, \newacronym is redefined to internally use \newabbreviation (with category=acronym). The other difference is that the short form is obtained using \glsxtrshort instead of \acrshort. (This allows for different abbreviation fonts.)
So your MWE can be changed to:
\documentclass{article}

\usepackage[xindy]{glossaries-extra}

\makeglossaries

\setabbreviationstyle[withoutdesc]{short-long}
\setabbreviationstyle[withdesc]{long-short-desc}

\newabbreviation[category=withoutdesc]{one}{one}{The number one}
\newabbreviation[category=withoutdesc]{two}{two}{The number two}
\newabbreviation[category=withdesc,
 description={Just a number with a meaningful description}]
 {three}{three}{The number three}

\newglossarystyle{customlist}{%
  \setglossarystyle{listhypergroup}%
  \renewcommand*{\glossentry}[2]{%
    \item[\glsentryitem{##1}%
      \glstarget{##1}{\glossentryname{##1}}]%
    \glsifcategory{##1}{withoutdesc}%
    { --- \glsentrylong{##1}}%
    {%
      \mbox{}\par\nobreak\csuse{@afterheading}%
      \glossentrydesc{##1}%
    }%
    \glspostdescription\space ##2%
  }%
}
\setglossarystyle{customlist}%

\begin{document}
The numbers \glsxtrshort{one}, \glsxtrshort{two} and \glsxtrshort{three}...

\printglossary[type=main]
\end{document}

This assigns two categories: withdesc for abbreviations with a description and withoutdesc for abbreviations without a description. This allows one style (short-long) to be applied to the abbreviations without a description and another style (long-short-desc) to be applied to the abbreviations with a description.
A new glossary style is also defined based on the listhypergroup style that checks the entry's category (using \glsifcategory) to determine whether or not to insert a paragraph break followed by the description.
I'm guessing that you've used \acrshort because you don't want expansion on first use. There are abbreviation styles that can automatically do this for you so that you can just use \gls instead.
In the first case (abbreviations with no descriptions), this can easily be achieved by replacing the short-long style with short-nolong:
\setabbreviationstyle[withoutdesc]{short-nolong}

For the withdesc category, there is a short-nolong-desc style but this would reverse the order in the name field. There isn't a nolong-short-desc style, but a style can be defined based on an existing style like this:
\newabbreviationstyle{nolong-short-desc}%
{% base it on short-nolong-desc:
  \GlsXtrUseAbbrStyleSetup{short-nolong-desc}%
}%
{% base it on long-short style:
  \GlsXtrUseAbbrStyleFmts{long-short}%
}

Now the style can be set for the withdesc category:
\setabbreviationstyle[withdesc]{nolong-short-desc}

The complete document is now:
\documentclass{article}

\usepackage[xindy]{glossaries-extra}

\makeglossaries

\newabbreviationstyle{nolong-short-desc}%
{% base it on short-nolong-desc:
  \GlsXtrUseAbbrStyleSetup{short-nolong-desc}%
}%
{% base it on long-short style:
  \GlsXtrUseAbbrStyleFmts{long-short}%
}

\setabbreviationstyle[withoutdesc]{short-nolong}
\setabbreviationstyle[withdesc]{nolong-short-desc}

\newabbreviation[category=withoutdesc]{one}{one}{The number one}
\newabbreviation[category=withoutdesc]{two}{two}{The number two}
\newabbreviation[category=withdesc,
 description={Just a number with a meaningful description}]
 {three}{three}{The number three}

\newglossarystyle{customlist}{%
  \setglossarystyle{listhypergroup}%
  \renewcommand*{\glossentry}[2]{%
    \item[\glsentryitem{##1}%
      \glstarget{##1}{\glossentryname{##1}}]%
    \glsifcategory{##1}{withoutdesc}%
    { --- \glsentrylong{##1}}%
    {%
      \mbox{}\par\nobreak\csuse{@afterheading}%
      \glossentrydesc{##1}%
    }%
    \glspostdescription\space ##2%
  }%
}
\setglossarystyle{customlist}%

\begin{document}
The numbers \gls{one}, \gls{two} and \gls{three}...

\printglossary[type=main]
\end{document}

The resulting document looks like:

You can provide your own shortcut command so that you don't need to keep setting the category key. For example:
% syntax: \mynewabbrv[options]{label}{short}{long}{description}
\newcommand*{\mynewabbrv}[5][]{%
  \ifblank{#5}%
  {\newabbreviation[category=withoutdesc,#1]{#2}{#3}{#4}}%
  {\newabbreviation[category=withdesc,description={#5},#1]{#2}{#3}{#4}}%
}

\mynewabbrv{one}{one}{The number one}{}
\mynewabbrv{two}{two}{The number two}{}
\mynewabbrv{three}{three}{The number three}
 {Just a number with a meaningful description}

This uses etoolbox's \ifblank to determine if the final argument is empty.
Alternatively, if you want to keep your original syntax:
\makeatletter
\define@key{mynewabbrv}{description}{\def\mydesc{#1}}
\makeatother

\renewcommand*{\newacronym}[4][]{%
  \def\mydesc{}%
  \setkeys*{mynewabbrv}{#1}%
  \ifdefempty{\mydesc}%
  {\newabbreviation[category=withoutdesc,#1]{#2}{#3}{#4}}%
  {\newabbreviation[category=withdesc,#1]{#2}{#3}{#4}}%
}

\newacronym{one}{one}{The number one}
\newacronym{two}{two}{The number two}
\newacronym[description={Just a number with a meaningful description}]
 {three}{three}{The number three}

This allows the description key to be extracted from the options list.


Q: .ajax, jquery, images that load late after upload I use .ajax jquery to upload images, but the images are still being uploaded when ajax finishes. The load event that is called after loads the same images. I have to refresh a few times before I get the right image.
I tried using setTimeout but it did not work. How can I fix this problem?
ADDED: As you can see, I tried using a timeout but it didn't work
$.ajax(
        {
            url:"<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>",
            type:"POST",
            data:X,
            cache:false,
            processData:false,
            contentType:false,
            beforeSend:function()
            {
                $('#MAIN').animate({opacity:0.2});
                $('#LOADING').fadeIn(250);
            },
            success:function()
            {
                setTimeout(function()
                {
                    $('#'+Y+'_LOAD').load('FRAME/image.php',{USER_CODE:Z,TYPE:Y},function()
                    {
                        $('#MAIN').animate({opacity:1});
                        $('#LOADING').fadeOut(250);

                        HEIGHT = $('#'+Y+'_LOAD').show().height();

                        $('#'+Y+'_SLIDE').animate({'height':HEIGHT-3},function()
                        {
                            $('#'+Y+'_LOAD').fadeIn(150);
                        });
                    });
                },5000);
            }
        });

A: The solution is no-cache the image or create something like this:
BANNER.jpg?V='.time();

BUT when using background image, it does not find the image. Anyone have a solution that, please post.


Q: List  store large amounts of data , Not enough memory public class ListKeywords
{
    public int ID { set; get; }
    public string Keyword { set; get; } //关键词
    public string Language { set; get; } //语种
    public int WordCount { set; get; } //单词数
    public int WordLength { set; get; } // 字符数
    public int Status { set; get; } //采集状态  0-未采集 1-采集成功 2-保存失败 3-保存成功 4-发布失败 5-发布成功
    public bool Taken { set; get; }
    public bool FTPStatus { set; get; }
    public bool DBStatus { set; get; }
    public string UrlName { set; get; }
    public ListKeywords()
    {
    }
    public ListKeywords(string keyword)
    {
        this.Keyword = keyword;
    }
}

List<string> lines = new List<string>();
List<ListKeywords> keywordsList = new List<ListKeywords>();

using (StreamReader sr = File.OpenText(filePath))
{
    string s = String.Empty;
    while ((s = sr.ReadLine()) != null)
    {
        //lines.Add(s);   //Operating normally
        eywordsList.Add(new ListKeywords("some keywords")); //  Operating normally
        keywordsList.Add(new ListKeywords(s)); // it will be out of memeory
    }
}

In text file, have 1,000,000 line data, if i use above code to load the large data to list< keywordsList >, it will raises an OutOfMemoryException, but if i load it to list< string >, it run normally.  How to solved it ?

A: Instead of using a List maybe try using an IEnumerable w/ yield?
static IEnumerable<ListKeywords> Keywords()
{
    using (StreamReader sr = File.OpenText(path))
    {
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
            yield return new ListKeywords(s);
        }
    }
}

Note that Jon Skeet's C# in Depth offers a great explanation about this in Chapter 6. I imagine he also has some articles or posts on StackOverflow about this topic. As he points out, you want to be careful about modifying this method to pass in a StreamReader (or TextReader as is used in his example) as you would want to take ownership of the reader so it will be properly disposed of. Rather, you would want to pass in a Func<StreamReader> if you have such a need. Another interesting note he adds here - which I will point out because there are some edge cases where the reader will not actually be properly disposed of even if you don't allow the reader to be provided by the caller - it's possible for the caller to abuse the IEnumerable<ListKeywords> by doing something like Keywords().GetEnumerator() - this could result in a memory leak and could even potentially cause security issues if you have security-related code which relies on the using statement to clean up the resource.


Q: PostgreSQL query by string is filtering even the values where there are nulls. I've created a table in PostgreSQL 9.5 as shown below and I added some data to it. However, when I try and query data by case insensitive search like !~* it removes even the null value rows. How can I do a query that will return all categories that are null and vegetables but not fruits?
CREATE TABLE temp
(
  category character varying,
  item character varying
);

INSERT INTO temp VALUES('Fruits', 'apple');
INSERT INTO temp VALUES('FRUITS', 'applE');
INSERT INTO temp(item) VALUES('Apple');
INSERT INTO temp(item) VALUES('BANANA');
INSERT INTO temp VALUES('Vegetables', 'Cabbage');

Query
Select * from temp where category !~* 'fruits'

Output
category   item
--------   --------
Vegetables Cabbage

A: To deal with the null you can use is distinct from:
Select *
from temp
where lower(category) is distinct from 'fruits'

or if you do want the regular expression:
Select *
from temp
where category !~* 'fruits'
  or category is null;

alternatively treat null as something else:
Select *
from temp
where coalesce(category, '') !~* 'fruits'


Q: Functions using Dictionary name and Key as argument qualifier_2 = {'KKR' : {'Chris Lynn': 4,
                      'Sunil Narine': 10,
                      'Gautam Gambhir (c)': 12,
                      'Robin Uthappa (wk)': 1,
                      'Ishank Jaggi': 28,
                      'Colin Grandhomme': 0,
                      'Suryakumar Yadav': 31,
                      'Piyush Chawla': 2,
                      'Nathan Coulter-Nile': 6,
                      'Umesh Yadav': 2,
                      'Ankit Rajpoot': 4,
                      'Extra runs': 7,
                      'Total batted': 10},
                'MI': {'Lendl Simmons': 3,
                      'Parthiv Patel (wk)': 14,
                      'Ambati Rayudu': 6,
                      'Rohit Sharma (c)': 26,
                      'Krunal Pandya': 45,
                      'Kieron Pollard': 9,
                      'Extra runs': 8,
                      'Total batted': 6}}

I want to write a function that takes dictionary and team as an argument and returns the total runs
i.e Dictionary -> qualifier_2 and Team -> KKR/MI
def total_runs(x,y):
    if x == 'qualifier_2' and y == 'KKR':
        c = sum(qualifier_2['KKR'].values())
    return c
total_runs(qualifier_2,KKR)

A: This isn't a function, But a way to aggregate all scores at once.
Run through the dictionary and sum the values as you go.
final_dict = {}
for team, scores in qualifier_2.items():
    final_dict[team] = 0 # initialize score to 0
    for player, score in scores.items():
        final_dict[team] += score # accumulate score as you loop

print(final_dict)

Outputs:
{'KKR': 117, 'MI': 117}

A: You call your function with the name of the dictionary
total_runs(qualifier_2,KKR)

Then you try to compare that to a string
    if x == 'qualifier_2' and ........ :

Identity comparisons: If you really want/need to ensure that it is the specific dictionary, change it to
    if x is qualifier_2 and y == 'KKR':

In a function, you want to use the name of the parameters used in the definition.  Inside your function (inside the function's scope) the dictionary you passed as the first argument has been assigned to x and the key you passed as the second argument was assigned to y.
        c = sum(x[y].values())

def total_runs(x,y):
    if x is qualifier_2 and y == 'KKR':
        c = sum(x[y].values())
    return c

Your dictionary keys are strings so you need to paa a string for that argument
total_runs(qualifier_2,'KKR')

Functions are used to make a process more generic so that process can be reused with different arguments/values passed to it's parameters.  While there may be some reasons to check for specific parameter values (maybe for debugging), usually it defeats the purpose of a function.
You could have written it like this:
def total_runs(x,y):
    c = sum(x[y].values())
    return c

or
def total_runs(x,y):
    return sum(x[y].values())

A: You can use dict.values() to get a list of the numbers, then pass it through sum to get the total:
qualifier_2 = {'KKR' : {'Chris Lynn': 4,
                      'Sunil Narine': 10,
                      'Gautam Gambhir (c)': 12,
                      'Robin Uthappa (wk)': 1,
                      'Ishank Jaggi': 28,
                      'Colin Grandhomme': 0,
                      'Suryakumar Yadav': 31,
                      'Piyush Chawla': 2,
                      'Nathan Coulter-Nile': 6,
                      'Umesh Yadav': 2,
                      'Ankit Rajpoot': 4,
                      'Extra runs': 7,
                      'Total batted': 10},
                'MI': {'Lendl Simmons': 3,
                      'Parthiv Patel (wk)': 14,
                      'Ambati Rayudu': 6,
                      'Rohit Sharma (c)': 26,
                      'Krunal Pandya': 45,
                      'Kieron Pollard': 9,
                      'Extra runs': 8,
                      'Total batted': 6}}

def total_runs(team):
    # If team is not found in the data, return 0.
    if team not in qualifier_2:
        return 0

    # Otherwise, find the team and return a sum of their values.
    return sum(qualifier_2[team].values())

print total_runs("KKR") # Output: 117
print total_runs("MI") # Output: 117

You can even simplify it as a one liner, though it might be less readable:
def total_runs(team):
    return sum((qualifier_2.get(team) or {}).values())

print total_runs("KKR") # Output: 117
print total_runs("MI") # Output: 117
print total_runs("FOOBAR") # Output: 0


Q: What is the big block of javascript that i see at the beginning of some html pages? I'm trying to increase my literacy of source code, however often times when I view page source for a site i will find a huge wall of what appears to be javascript code.
A good example would be this site:
http://www.torontossc.com/
When I view the page source, I have no idea how to deal with that huge wall, so I have a few questions/logical deductions.

*

*The code wall is in <script> tags, so I'm assuming it must be javascript. But I'm confused about why it's presented in such an unreadable/cluttered format. Surely there must be a reason for that.

*I downloaded the source code and looked at the html page, and noticed that when I'm not viewing the source at run time, that block isn't there- There's only an externally referenced script in its place. So is the wall of code I'm seeing the actual script itself, that runs on page load?

*I did further digging and found out that the script is part of the facebook sdk. So does this mean that any time i see a wall of code like this, it's usually a script imported for use as part of an API/for integration with another website? If that's the case, then should i assume that the clutter and density of it is just for compactness

*If my above assumptions are correct, then would learning javascript allow me to fully understand that code wall?
I hope I've answered my own question through deduction, but hopefully someone can confirm.
Thanks!

A:
The code wall is in tags, so I'm assuming it must be javascript.

Yes, it's clearly printed right there: <script type="text/javascript">.

But I'm confused about why it's presented in such an unreadable/cluttered format. Surely there must be a reason for that.

It's minified, a form of obfuscation which makes JavaScript smaller to download and more difficult to reverse engineer.

I downloaded the source code and looked at the html page...

That probably broke a lot of things. You can't just download a page without downloading all of it's relatively-referenced paths.

So does this mean that any time i see a wall of code like this, ...

No, there's nothing you can tell about the code except that it's

*

*inline

*minified

If my above assumptions are correct, then would learning javascript allow me to fully understand that code wall?

No, nobody writes code that way, and nobody (easily) understands code written that way. A computer compressed/minified the code, and to understand it you need to learn JavaScript, and then unminify the code, which is a far from perfect process. Many forms of minification are "destructive" in that it's impossible to arrive back at the original source code. Human-readable tokens are often turned into single characters, and there is no way to undo this process, the original human-readable names are lost.


Q: How To Add A Back Slash To The TextBox For Date Format This Is My JavaScript:
`
function ValidateDate(txt, keyCode)
        {
            if(keyCode==16)
                isShift = false;
            var val=txt.value;
            var lblmesg = document.getElementById("<%=lblMesg.ClientID%>") ;
            if(val.length == 10)
            {
                var splits = val.split("/");
                var dt = new Date(splits[1] + "/" + splits[0] + "/" + splits[2]);

                //Validation for Dates
                if(dt.getDate()==splits[0] && dt.getMonth()+1==splits[1] && dt.getFullYear()==splits[2])
                {
                    lblmesg.style.color="green";
                    lblmesg.innerHTML = "Valid Date";
                }
                else
                {
                    lblmesg.style.color="red";
                    lblmesg.innerHTML = "InValid Date";
                    return;
                }

                //Range Validation
                if(txt.id.indexOf("txtRange") != -1)
                    RangeValidation(dt);

                //BirthDate Validation
                if(txt.id.indexOf("txtBirthDate") != -1)
                    BirthDateValidation(dt)
            }
            else if(val.length < 10)
            {
                lblmesg.style.color="blue";
                lblmesg.innerHTML = "Required dd/mm/yy format. Slashes will come up automatically.";
            }
        }`

And This Is My TextBox:
> <asp:TextBox ID="txtValidate" runat="server" MaxLength = "10" onkeyup = "ValidateDate(this, event.keyCode)" onkeydown = "return DateFormat(this, event.keyCode)"></asp:TextBox>

I want to include a slash within a TextBox for typing a Date.. I don't want it to generate a slash while typing...it should be static when the page is loaded.... Is it possible to do that without using AjaxToolkit ???

A: I use this simple replace

Date: <input name=x size=10 maxlength=10  onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')">

Try it with jsfiddle

A: I made a simple example for your purpose:
var date = document.getElementById('date');

date.addEventListener('keypress', function (event) {
    var char = String.fromCharCode(event.which),
        offset = date.selectionStart;

    if (/\d/.test(char) && offset < 8) {

        if (offset === 2 || offset === 5) {
            offset += 1;
        }
        date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1);
        date.selectionStart = date.selectionEnd = offset + 1;
    }

    if (!event.keyCode) {
        event.preventDefault();
    }
});

Here is a fiddle

A: Here is a shorter version:
    $("#txtDate").keyup(function(){
      if ($(this).val().length == 2 || $(this).val().length == 5){
         $(this).val($(this).val() + "/");
      }
   });


Q: Scale image in CVImageBuffer I have a task - to scale down an image which I got from the camera. I need it in order to do heavy-lifting operations on smaller version of the image which will help me to save some processing power.
I decided to go with vImage_Buffer from Accelerate. Here's my code with few comments just to give clear understanding what is what there:
        guard let imgBuffer = CMSampleBufferGetImageBuffer(buffer) else {
            return
        }

        CVPixelBufferLockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        // create vImage_Buffer out of CVImageBuffer
        var inBuff: vImage_Buffer = vImage_Buffer()
        inBuff.width = UInt(CVPixelBufferGetWidth(imgBuffer))
        inBuff.height = UInt(CVPixelBufferGetHeight(imgBuffer))
        inBuff.rowBytes = CVPixelBufferGetBytesPerRow(imgBuffer)
        inBuff.data = CVPixelBufferGetBaseAddress(imgBuffer)

        // bring down the size at half
        let new_width: UInt = inBuff.width/2
        let new_height: UInt = inBuff.height/2

        // create output buffer where scaled image is supposed to be
        var outBuff: vImage_Buffer = vImage_Buffer()
        outBuff.data = UnsafeMutableRawPointer.allocate(byteCount: Int(new_width * new_height * 4), alignment: MemoryLayout<UInt>.size)
        outBuff.width = new_width
        outBuff.height = new_height
        outBuff.rowBytes = Int(new_width * 4)

        // perform scale
        let err = vImageScale_ARGB8888(&inBuff, &outBuff, nil, 0)
        if err != kvImageNoError {
            print("Wrong!")
        }

        // I guess I need to unlock buffer at this point, right?
        CVPixelBufferUnlockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        // create CVImageBuffer
        let options = [kCVPixelBufferCGImageCompatibilityKey: true,
                       kCVPixelBufferCGBitmapContextCompatibilityKey: true,
                       kCVPixelBufferWidthKey: new_width,
                       kCVPixelBufferHeightKey: new_height] as CFDictionary

        var newPixelBuffer: CVImageBuffer?
        let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
                                                  Int(new_width), Int(new_height),
                                                  kCVPixelFormatType_32BGRA, &outBuff, Int(new_width * 4),
                                                  nil, nil, options, &newPixelBuffer)

        if status == kCVReturnError {
            print("Wrong again!")
        }

        // create CIImage from CVImageBuffer and UIImage from CIImage just to see how scale went
        let ciImg = CIImage(cvImageBuffer: newPixelBuffer!)
        let img = UIImage(ciImage: ciImg)
        delegate?.testSmallImage(img)

It seems like all operations are performed without any errors and I want to check how scale went so I'm trying to create new UIImage out of scaled buffer. But when I try to show an image with UIImageView, I have EXC_BAD_ACCESS error. And when I try to save brand-new UIImage, everything goes without errors, but no file appears in Documents directory. Can you point me out what exactly am I doing wrong here? Thanks!

A: Here's the code snippet on Swift which resizes CMSampleBuffer:
    private func scale(_ sampleBuffer: CMSampleBuffer) -> CVImageBuffer?
    {
        guard let imgBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            return nil
        }

        CVPixelBufferLockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        // create vImage_Buffer out of CVImageBuffer
        var inBuff: vImage_Buffer = vImage_Buffer()
        inBuff.width = UInt(CVPixelBufferGetWidth(imgBuffer))
        inBuff.height = UInt(CVPixelBufferGetHeight(imgBuffer))
        inBuff.rowBytes = CVPixelBufferGetBytesPerRow(imgBuffer)
        inBuff.data = CVPixelBufferGetBaseAddress(imgBuffer)

        // perform scale
        var err = vImageScale_ARGB8888(&inBuff, &scaleBuffer, nil, 0)
        if err != kvImageNoError {
            print("Can't scale a buffer")
            return nil
        }
        CVPixelBufferUnlockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        var newBuffer: CVPixelBuffer?
        let attributes : [NSObject:AnyObject] = [
            kCVPixelBufferCGImageCompatibilityKey : true as AnyObject,
            kCVPixelBufferCGBitmapContextCompatibilityKey : true as AnyObject
        ]

        let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
                                                  Int(scaleBuffer.width), Int(scaleBuffer.height),
                                                  kCVPixelFormatType_32BGRA, scaleBuffer.data,
                                                  Int(scaleBuffer.width) * 4,
                                                  nil, nil,
                                                  attributes as CFDictionary?, &newBuffer)

        guard status == kCVReturnSuccess, let b = newBuffer else {
            print("Can't create new CVPixelBuffer")
            return nil
        }

        return b
    }

And here's a definition of scaleBuffer which acts as a destination in scale operation. I do not need to create it each scale so I do it only once:
        scaleBuffer.data = UnsafeMutableRawPointer.allocate(byteCount: Int(new_width * new_height * 4), alignment: MemoryLayout<UInt>.size)
        scaleBuffer.width = vImagePixelCount(new_width)
        scaleBuffer.height = vImagePixelCount(new_height)
        scaleBuffer.rowBytes = Int(new_width * 4)


Q: paint on a container being added to jcomponent i have a jrame on which i add some JComponent objects.
Each JComponent has a list of containers i add by using JComponent.add( Component).
Now in my main JComponent class, called MyComponent, i override the protected method paintComponent where i can paint things, which works pretty fine.
But i dont want to paint on the main JComponent, i only want to paint on the containers i have added to my main JComponent.
So in MyComponent in paintComponent i do the following.
protected void paintComponent( Graphics g) {
  super.paintComponent( g);

  Graphics page_g = this.getPage( "main").getGraphics();

  page_g.setColor( Color.RED);
  page_g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
  page_g.setColor( Color.BLUE);
  page_g.drawString( "HELLO WORLD", this.getWidth() / 2, this.getHeight() / 2);
}

The line this.getPage( "main").getGraphics(); takes the Graphics object from one of my containers added to the MyComponents list of containers and of course to the main component list using JComponents add method. The container is set to visible by calling the setVisible( true); method.
But nothing happens. The screen is empty. When i replace page_g with g, then painting works, because its painting on my JComponent (MyComponent), but i want to paint on the container which is a children of MyComponent in this case.
I often heard "Never use getGraphics()". But how else can ONLY draw on sub components of a parent component when the parents paintComponent method gets called?

A: Really the best bet is to have the classes that are actually doing the custom painting override their own paintComponent() method.  Let the AWT worry about the graphics contexts.


Q: Parameterized Async function returning Promise { "_40": 0, "_55": "English", "_65": 1, "_72": null, } [CLOSED]
How to get the 'English' out of the promise object which is unneccesary

Async Functions -> parameterized

const getLanguageNamefromCode = async (lng_code) => {
  let response, langData, lang;
  try {
    response = await fetch(
      `https://restcountries.eu/rest/v2/lang/${lng_code}?fields=languages`
    );
    langData = await response.json();
    // console.log(langData[0].languages[0]);
    if (langData[0].languages[0].iso639_1 === lng_code) {
      lang = langData[0].languages[0].name;
      console.log(lang);
    }
    return lang;
  } catch (err) {
    throw new Error(err);
  }
};

calling it from inside a for loop and sending in a parameter

      const loadedTrendingMovies = [];
      const loadedTrendingMoviesLength = trendingMovies.results.length;

      for (let i = 0; i < 6; i++) {
        // let credits;
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) =>
            userMovie.id === trendingMovies.results[i].id.toString()
        );

        loadedTrendingMovies.push(
          new Movie(
            trendingMovies.results[i].id.toString(),
            trendingMovies.results[i].media_type === "movie"
              ? trendingMovies.results[i].title
              : trendingMovies.results[i].name,
            posterBaseUrl + trendingMovies.results[i].poster_path,
            trendingMovies.results[i].media_type === "movie"
              ? trendingMovies.results[i].release_date
              : trendingMovies.results[i].first_air_date,
            [],
            trendingMovies.results[i].overview,
            trendingMovies.results[i].vote_average,
            getLanguageNamefromCode(trendingMovies.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

How to get the value from the promise returned by the getLanguagefromCode Async Method.

This is my MoviesScreen functional component , i am using redux

import React, { useEffect, useCallback, useState, useRef } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  ScrollView,
  StatusBar,
  TouchableWithoutFeedback,
  RefreshControl,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import MovieItem from "../components/MovieItem";
import { useSelector, useDispatch } from "react-redux";
import * as MoviesAction from "../store/actions/MoviesAction";
import * as UserActions from "../store/actions/UserActions";
import Colors from "../constants/Colors";

import { useScrollToTop } from "@react-navigation/native";

import SkeletonContent from "react-native-skeleton-content";
import { createSelector } from "reselect";

const stories = createSelector(
  (state) => state.Movies.movies,
  (movies) => movies
);
const newReleases = createSelector(
  (state) => state.Movies.new_releases,
  (new_releases) => new_releases
);
const newTVShows = createSelector(
  (state) => state.Movies.new_tv_shows,
  (new_tv_shows) => new_tv_shows
);
const Anime = createSelector(
  (state) => state.Movies.anime,
  (anime) => anime
);
const MoviesScreen = (props) => {
  const Stories = useSelector(stories);
  const new_releases = useSelector(newReleases);
  console.log(" movie screen rendered", new_releases);
  const new_tv_shows = useSelector(newTVShows);
  const anime = useSelector(Anime);

  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const dispatch = useDispatch();
  const scrollRef = useRef(null);

  useScrollToTop(scrollRef);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    loadScreen().then(() => setRefreshing(false));
  }, [setRefreshing, loadScreen]);

  const loadScreen = useCallback(async () => {
    try {
      dispatch(MoviesAction.loadAll());
    } catch (err) {
      console.log(err);
    }
  }, []);

  useEffect(() => {
    setLoading(true);
    loadScreen().then(() => setLoading(false));
  }, []);

  const renderTrendingMoviesItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={styles.new_releases}
      isLoading={loading || refreshing}
      layout={[styles.cinemaSkeleton]}
    >
      <MovieItem
        style={styles.new_releases}
        id={item.id}
        movieTitle={item.title}
        posterUrl={item.posterUrl}
        year={item.year}
        onPress={() => {
          props.navigation.navigate({
            name: "MoviesDetailScreen",
            params: {
              movieId: item.id,
              movieTitle: item.title,
              moviesType: "Movies",
            },
          });
        }}
      />
    </SkeletonContent>
  );

  const renderStoriesItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={{
        ...styles.storyItem,
        marginHorizontal: 10,
        marginVertical: 7.5,
      }}
      isLoading={loading || refreshing}
      layout={[
        {
          key: "story",
          width: 80,
          height: 80,
          borderRadius: 40,
          marginHorizontal: 10,
          marginVertical: 7.5,
        },
      ]}
    >
      <MovieItem
        style={styles.storyItem}
        footerStyle={{ opacity: 0 }}
        imageStyle={styles.storyImage}
        id={item.id}
        posterUrl={item.posterUrl}
        onPress={() => {
          props.navigation.navigate({
            name: "NewReleasesModalScreen",
            params: {
              movieTitle: item.title,
              posterUrl: item.posterUrl,
              movieId: item.id,
            },
          });
        }}
      />
    </SkeletonContent>
  );

  const renderTrendingTVItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={styles.new_releases}
      isLoading={loading || refreshing}
      layout={[styles.cinemaSkeleton]}
    >
      <MovieItem
        style={styles.new_releases}
        id={item.id}
        movieTitle={item.title}
        posterUrl={item.posterUrl}
        year={item.year}
        onPress={() => {
          props.navigation.navigate({
            name: "MoviesDetailScreen",
            params: {
              movieId: item.id,
              movieTitle: item.title,
              moviesType: "TV",
            },
          });
        }}
      />
    </SkeletonContent>
  );

  const renderAnimeItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={styles.new_releases}
      isLoading={loading || refreshing}
      layout={[styles.cinemaSkeleton]}
    >
      <MovieItem
        style={styles.new_releases}
        id={item.id}
        movieTitle={item.title}
        posterUrl={item.posterUrl}
        year={item.year}
        onPress={() => {
          props.navigation.navigate({
            name: "MoviesDetailScreen",
            params: {
              movieId: item.id,
              movieTitle: item.title,
              moviesType: "anime",
              goToAnime: true,
            },
          });
        }}
      />
    </SkeletonContent>
  );

  return (
    <ScrollView
      ref={scrollRef}
      style={styles.screen}
      showsVerticalScrollIndicator={false}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          tintColor={Colors.lightblue}
        />
      }
    >
      {/* new releases stories */}
      <StatusBar barStyle="light-content" />
      <SkeletonContent
        boneColor="#303030"
        highlightColor="#252525"
        containerStyle={styles.headerCont}
        isLoading={loading || refreshing}
        layout={[styles.headerTextSkeleton]}
      >
        <View style={styles.headerCont}>
          <Text style={styles.headerText}> New Releases </Text>
        </View>
      </SkeletonContent>
      <View>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={Stories}
          renderItem={renderStoriesItem}
        />
      </View>

      {/* new releases stories */}
      {/*...

      TOP MOVIE THAT WEEK

      ...
      */}

      <View>
        <SkeletonContent
          boneColor="#303030"
          containerStyle={styles.headerCont}
          highlightColor="#252525"
          containerStyle={styles.headerCont}
          isLoading={loading || refreshing}
          layout={[styles.headerTextSkeleton]}
        >
          <View style={styles.headerCont}>
            <TouchableWithoutFeedback
              onPress={() => {
                props.navigation.navigate({
                  name: "SeeAllScreen",
                  params: {
                    new_releases: true,
                    headerTitle: "Trending Movies",
                  },
                });
              }}
            >
              <View style={{ flexDirection: "row" }}>
                <Text style={styles.headerText}> Movies </Text>
                <Ionicons
                  style={{ marginStart: 5 }}
                  name="ios-arrow-forward"
                  size={22}
                  color={Colors.lightblue}
                />
              </View>
            </TouchableWithoutFeedback>
          </View>
        </SkeletonContent>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={new_releases}
          renderItem={renderTrendingMoviesItem}
        />
      </View>

      {/* TV SHOWS */}

      <View>
        <SkeletonContent
          boneColor="#303030"
          containerStyle={styles.headerCont}
          highlightColor="#252525"
          containerStyle={styles.headerCont}
          isLoading={loading || refreshing}
          layout={[styles.headerTextSkeleton]}
        >
          <View style={styles.headerCont}>
            <TouchableWithoutFeedback
              onPress={() => {
                props.navigation.navigate({
                  name: "SeeAllScreen",
                  params: {
                    new_tv_shows: true,
                    headerTitle: "Trending TV Shows",
                  },
                });
              }}
            >
              <View style={{ flexDirection: "row" }}>
                <Text style={styles.headerText}> TV Shows </Text>
                <Ionicons
                  style={{ marginStart: 5 }}
                  name="ios-arrow-forward"
                  size={22}
                  color={Colors.lightblue}
                />
              </View>
            </TouchableWithoutFeedback>
          </View>
        </SkeletonContent>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={new_tv_shows}
          renderItem={renderTrendingTVItem}
        />
      </View>

      {/* Anime */}

      <View>
        <SkeletonContent
          boneColor="#303030"
          containerStyle={styles.headerCont}
          highlightColor="#252525"
          containerStyle={styles.headerCont}
          isLoading={loading || refreshing}
          layout={[styles.headerTextSkeleton]}
        >
          <View style={styles.headerCont}>
            <TouchableWithoutFeedback
              onPress={() => {
                props.navigation.navigate({
                  name: "SeeAllScreen",
                  params: {
                    moviesType: "anime",
                    goToAnime: true,
                    headerTitle: "Trending Anime",
                  },
                });
              }}
            >
              <View style={{ flexDirection: "row" }}>
                <Text style={styles.headerText}> Anime </Text>
                <Ionicons
                  style={{ marginStart: 5 }}
                  name="ios-arrow-forward"
                  size={22}
                  color={Colors.lightblue}
                />
              </View>
            </TouchableWithoutFeedback>
          </View>
        </SkeletonContent>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={anime}
          renderItem={renderAnimeItem}
        />
      </View>
    </ScrollView>
  );
};

This is the actions file

import React, { useState } from "react";

export const SEARCH_MOVIES = "SEARCH_MOVIES";
export const LOAD_MOVIES_WITH_GENRES = "LOAD_MOVIES_WITH_GENRES";
export const CLEAR_SEARCH_LIST = "CLEAR_SEARCH_LIST";
export const CLEAR_GENRE_SCREEN = "CLEAR_GENRE_SCREEN";
export const LOAD_ALL = "LOAD_ALL";

import Movie from "../../models/Movie";

import config from "../../config";
import Cast from "../../models/CastMember";

const getCredits = async (index) => {
  let response, creditsData;
  try {
    response = await fetch(
      `https://api.themoviedb.org/3/tv/${resData.results[index].id}?api_key=${config.TMDB_API_KEY}&language=en-US&append_to_response=credits`
    );
    creditsData = await response.json();
    // console.log("credits", creditsData);
  } catch (err) {
    throw new Error(err);
  }

  const castMembers = [];
  const length =
    creditsData.credits.cast.length > 10 ? 10 : creditsData.credits.cast.length;

  for (let i = 0; i < 6; i++) {
    castMembers.push(
      new Cast(
        creditsData.credits.cast[i].id,
        creditsData.credits.cast[i].character,
        creditsData.credits.cast[i].name,
        posterBaseUrl + creditsData.credits.cast[i].profile_path
      )
    );
  }

  console.log(castMembers);

  return { cast: castMembers };
};

const getLanguageNamefromCode = async (lng_code) => {
  let response, langData, lang;
  try {
    response = await fetch(
      `https://restcountries.eu/rest/v2/lang/${lng_code}?fields=languages`
    );
    langData = await response.json();
    // console.log(langData[0].languages[0]);
    if (langData[0].languages[0].iso639_1 === lng_code) {
      lang = langData[0].languages[0].name;
      console.log(lang);
    }
    return lang;
  } catch (err) {
    throw new Error(err);
  }
};

export const clearSearchList = () => {
  return { type: CLEAR_SEARCH_LIST };
};

export const clearGenreScreen = () => {
  return {
    type: CLEAR_GENRE_SCREEN,
  };
};

export const loadAll = () => {
  const posterBaseUrl = "http://image.tmdb.org/t/p/w185";
  let hasUserSaved;
  const loadedStories = [];
  return async (dispatch, getState) => {
    try {
      //stories response
      const moviesResponse = await fetch(
        `https://www.omdbapi.com/?apikey=${config.OMDB_API_KEY}&s=tokyo`
      );
      // trending movies
      const TrendingMoviesResponse = await fetch(
        `https://api.themoviedb.org/3/trending/all/day?api_key=${config.TMDB_API_KEY}`
      );
      // trending TV
      const trendingTVResponse = await fetch(
        `https://api.themoviedb.org/3/discover/tv?api_key=${config.TMDB_API_KEY}&language=en-US&sort_by=popularity.desc&first_air_date_year=2020&page=1&with_original_language=en`
      );
      // trending Anime
      const trendingAnimeResponse = await fetch(
        `https://kitsu.io/api/edge/trending/anime`,
        {
          method: "GET",
        }
      );

      if (
        !moviesResponse.ok ||
        !TrendingMoviesResponse.ok ||
        !trendingTVResponse.ok ||
        !trendingAnimeResponse.ok
      ) {
        throw new Error("failed response");
      }

      const movies = await moviesResponse.json();
      const trendingMovies = await TrendingMoviesResponse.json();
      const trendingTV = await trendingTVResponse.json();
      const trendingAnime = await trendingAnimeResponse.json();
      // console.log('Trending Movies',resData);
      // console.log("NEW RELEASES", resData);

      //stories array

      const loadedMoviesLength = movies.Search.length;

      for (let i = 0; i < 6; i++) {
        loadedStories.push(
          new Movie(
            movies.Search[i].imdbID,
            movies.Search[i].Title,
            movies.Search[i].Poster,
            movies.Search[i].Year
          )
        );
      }

      //trending movies array

      // console.log("loadedTrendingMovies", loadedTrendingMovies);
      let loadedTrendingMovies=[];

      const loadedTrendingMoviesLength = trendingMovies.results.length;

      // loadedTrendingMovies =
      Promise.all(
        trendingMovies.results
          .slice(0, 5) // use slice instead of a loop
          .map((
            trendingMovie // map movie to [language,movie]
          ) =>
            getLanguageNamefromCode(
              // get async language
              trendingMovie.original_language
              // resolve to [language,movie]
            ).then((language) => [language, trendingMovie])
          ) // sorry, forgot to return here
      )
        .then((
          results // results is [[language,movie],[language,movie]]
        ) =>
          results.map(([language, trendingMovie]) => {
            const hasUserSaved = getState().UserMovies.userMovies.find(
              (userMovie) => userMovie.id === trendingMovie.id.toString()
              // snippet does not have conditional chaining
            );
            return new Movie( // create new Movie
              trendingMovie.id.toString(),
              trendingMovie.media_type === "movie"
                ? trendingMovie.title
                : trendingMovie.name,
              posterBaseUrl + trendingMovie.poster_path,
              trendingMovie.media_type === "movie"
                ? trendingMovie.release_date
                : trendingMovie.first_air_date,
              [],
              trendingMovie.overview,
              trendingMovie.vote_average,
              language,
              hasUserSaved ? hasUserSaved.location : ""
            );
          })
        )
        .then((movies) => {
          // loadedTrendingMovies.push(movies);
          loadedTrendingMovies = [...loadedTrendingMovies, ...movies];
          console.log("loadedTrendingMovies", loadedTrendingMovies);
        })
        .catch((err) => console.log(err));

      // trending TV Shows
      const loadedNewTVShows = [];
      const TVShowsLength = trendingTV.results.length;

      for (let i = 0; i < 6; i++) {
        // let credits;
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === trendingTV.results[i].id.toString()
        );
        // let cast = getCredits(i).then((cast) => cast);
        // console.log("CAST", cast);
        loadedNewTVShows.push(
          new Movie(
            trendingTV.results[i].id.toString(),
            trendingTV.results[i].name,
            posterBaseUrl + trendingTV.results[i].poster_path,
            trendingTV.results[i].first_air_date.toString().substr(0, 5),
            // getCredits(i).then((cast) => cast),
            // getCredits(i)
            //   .then((results) => {
            //     console.log("success", results.cast);
            //     return results.cast;
            //   })
            //   .catch((err) => console.log("cast error", err)),
            [],
            trendingTV.results[i].overview,
            trendingTV.results[i].vote_average,
            // getLanguageNamefromCode(trendingTV.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

      const loadedAnime = [];
      const AnimeLength = trendingAnime.data.length;

      for (let i = 0; i < 6; i++) {
        // let credits;
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === trendingAnime.data[i].id.toString()
        );
        // let cast = getCredits(i).then((cast) => cast);
        // console.log("CAST", cast);
        loadedAnime.push(
          new Movie(
            trendingAnime.data[i].id,
            trendingAnime.data[i].attributes.canonicalTitle,
            trendingAnime.data[i].attributes.posterImage.medium,
            trendingAnime.data[i].attributes.createdAt.toString().substr(0, 4),
            // getCredits(i).then((cast) => cast),
            [],
            trendingAnime.data[i].attributes.synopsis,
            trendingAnime.data[i].attributes.vote_average,
            "Japanese",
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

      dispatch({
        type: LOAD_ALL,
        movies: loadedStories,
        new_releases: loadedTrendingMovies,
        new_tv_shows: loadedNewTVShows,
        anime: loadedAnime,
      });
    } catch (err) {
      console.log(err);
    }
  };
};

export const searchMovies = (MovieTitle) => {
  let response;
  let hasUserSaved;
  const posterBaseUrl = "http://image.tmdb.org/t/p/w185";
  return async (dispatch, getState) => {
    try {
      response = await fetch(
        `https://api.themoviedb.org/3/search/movie?api_key=${config.TMDB_API_KEY}&query=${MovieTitle}&page=1`
      );

      if (!response.ok) {
        throw new Error("failed response");
      }

      const resData = await response.json();
      console.log("search results: ", resData);

      const searchedMovies = [];
      const length = resData.results.length;

      for (i = 0; i < length; i++) {
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === resData.results[i].id
        );
        searchedMovies.push(
          new Movie(
            resData.results[i].id.toString(),
            resData.results[i].title,
            posterBaseUrl + resData.results[i].poster_path,
            resData.results[i].release_date,
            // getCredits(i).then((cast) => cast),
            [],
            resData.results[i].overview,
            resData.results[i].vote_average,
            // getLanguageNamefromCode(resData.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }
      dispatch({
        type: SEARCH_MOVIES,
        searched_movies: searchedMovies,
      });
    } catch (err) {
      console.log(err);
    }
  };
};

export const loadMoviesWithGenres = (genreId) => {
  let response;
  let hasUserSaved;
  const posterBaseUrl = "http://image.tmdb.org/t/p/w185";
  return async (dispatch, getState) => {
    await dispatch(clearGenreScreen());
    try {
      response = await fetch(
        `https://api.themoviedb.org/3/discover/movie?with_genres=${genreId}&api_key=${config.TMDB_API_KEY}`
      );

      if (!response.ok) {
        throw new Error("failed response");
      }

      const resData = await response.json();
      // console.log(resData);

      const loadedMoviesWRTGenre = [];
      const length = resData.results.length;

      for (let i = 0; i < length; i++) {
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === resData.results[i].id.toString()
        );
        // let cast = getCredits(i).then((cast) => cast)
        // console.log("CAST", cast);
        loadedMoviesWRTGenre.push(
          new Movie(
            resData.results[i].id.toString(),
            resData.results[i].title,
            posterBaseUrl + resData.results[i].poster_path,
            resData.results[i].release_date,
            // cast,
            // getCredits(i),
            [],
            resData.results[i].overview,
            resData.results[i].vote_average,
            // getLanguageNamefromCode(resData.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

      console.log("moviesWRTGenre", loadedMoviesWRTGenre);

      dispatch({
        type: LOAD_MOVIES_WITH_GENRES,
        moviesWRTGenre: loadedMoviesWRTGenre,
      });
    } catch (err) {
      console.log(err);
    }
  };
};

when i am logging the array in the actions file, it shows the perfect result , i.e.,

loadedTrendingMovies Array [
  Movie {
    "cast": Array [],
    "id": "385103",
    "language": "English",
    "location": "",
    "plot": "In Scooby-Doo’s greatest adventure yet, see the never-before told story of how lifelong friends Scooby and Shaggy first met and how they joined forces with young detectives Fred, Velma, and Daphne to form the famous Mystery Inc. Now, with hundreds of cases solved, Scooby and the gang face their biggest, toughest mystery ever: an evil plot to unleash the ghost dog Cerberus upon the world. As they race to stop this global “dogpocalypse,” the gang discovers that Scooby has a secret legacy and an epic destiny greater than anyone ever imagined.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/zG2l9Svw4PTldWJAzC171Y3d6G8.jpg",
    "ratings": 8.3,
    "title": "Scoob!",
    "year": "2020-05-15",
  },
  Movie {
    "cast": Array [],
    "id": "79680",
    "language": "English",
    "location": "",
    "plot": "Set more than seven years after the world has become a frozen wasteland, the remnants of humanity inhabit a gigantic, perpetually-moving train that circles the globe as class warfare, social injustice and the politics of survival play out.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/n6UNHZoiYj81abwmG38HbNjflDx.jpg",
    "ratings": 3,
    "title": "Snowpiercer",
    "year": "2020-05-17",
  },
  Movie {
    "cast": Array [],
    "id": "80986",
    "language": "English",
    "location": "",
    "plot": "Courtney Whitmore, a smart, athletic and above all else kind girl, discovers her step-father has a secret; he used to be the sidekick to a superhero. \"Borrowing\" the long-lost hero’s cosmic staff, she becomes the unlikely inspiration for an entirely new generation of superheroes.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/JJxVsQPPiuLcArALotMHsCubeo.jpg",
    "ratings": 9,
    "title": "Stargirl",
    "year": "2020-05-18",
  },
  Movie {
    "cast": Array [],
    "id": "530915",
    "language": "English",
    "location": "",
    "plot": "At the height of the First World War, two young British soldiers must cross enemy territory and deliver a message that will stop a deadly attack on hundreds of soldiers.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/AuGiPiGMYMkSosOJ3BQjDEAiwtO.jpg",
    "ratings": 7.9,
    "title": "1917",
    "year": "2019-12-25",
  },
  Movie {
    "cast": Array [],
    "id": "582596",
    "language": "English",
    "location": "",
    "plot": "A guy meets the woman of his dreams and invites her to his company's corporate retreat, but realizes he sent the invite to the wrong person.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/A2YlIrzypvhS3vTFMcDkG3xLvac.jpg",
    "ratings": 6.1,
    "title": "The Wrong Missy",
    "year": "2020-05-13",
  },
]

so i console log in the beginning of the MovieScreen Components (it is the first screen that loads up when my react native app launches) to see if the array is empty

 movie screen rendered Array []
 movie screen rendered Array []
 movie screen rendered Array []
 movie screen rendered Array []

Also i do not know why did it console logged i.e., re-rendered 4 times ,
  do you have any ideas ?

Here is its github repository if you want to check just npm install with expo

A:
The following should work (please note that this also returns a promise that resolves to an array of movies).

   const loadedTrendingMovies = await Promise.all(
      trendingMovies.results
        .slice(0, 5) // use slice instead of a loop
        .map((trendingMovie) => // map movie to [language,movie]
          getLanguageNamefromCode(// get async language
            trendingMovie.original_language
          // resolve to [language,movie]
          ).then((language) => [language, trendingMovie])
        ) // sorry, forgot to return here
    ).then((results) => // results is [[language,movie],[language,movie]]
      results.map(
        ([language, trendingMovie]) =>
          new Movie( // create new Movie
            trendingMovie.id.toString(),
            trendingMovie.media_type === 'movie'
              ? trendingMovie.title
              : trendingMovie.name,
            posterBaseUrl + trendingMovie.poster_path,
            trendingMovie.media_type === 'movie'
              ? trendingMovie.release_date
              : trendingMovie.first_air_date,
            [],
            trendingMovie.overview,
            trendingMovie.vote_average,
            language,
            getState().UserMovies.userMovies.find(
              (userMovie) =>
                userMovie.id === trendingMovie.id.toString()
            // if you don't have optional chaining you can get location
            //  first the way you did before
            )?.location || ''
          )
      )
    );

Working example

const trendingMovies = {
  results: [
    {
      original_language: 1,
      id: 1,
    },
    {
      original_language: 2,
      id: 2,
    },
  ],
};
const getLanguageNamefromCode = (lang) =>
  Promise.resolve(`language is: ${lang}`);
function Movie(id, language, location) {
  this.id = id;
  this.language = language;
  this.location = location;
}
const getState = () => ({
  UserMovies: {
    userMovies: [{ id: '1', location: 'location 1' }],
  },
});
Promise.all(
  trendingMovies.results
    .slice(0, 5) // use slice instead of a loop
    .map((trendingMovie) =>
      // map movie to [language,movie]
      getLanguageNamefromCode(
        // get async language
        trendingMovie.original_language
        // resolve to [language,movie]
      ).then((language) => [language, trendingMovie])
    )
)
  .then((
    results // results is [[language,movie],[language,movie]]
  ) =>
    results.map(([language, trendingMovie]) => {
      const userMovie = getState().UserMovies.userMovies.find(
        (userMovie) =>
          userMovie.id === trendingMovie.id.toString()
        // snippet does not have conditional chaining
      );
      return new Movie( // create new Movie
        trendingMovie.id.toString(),
        language,
        userMovie ? userMovie.location : ''
      );
    })
  )
  .then((movies) => console.log('movies:', movies));


Q: Validation Summary vertical alignment I have a two column layout page with a Validation Summary (VS) control above the 2 columns. The VS is centered in the container above the columns, which is what I want, but I also want the different bullet points to be vertically aligned, if possible. I have tried several things, including placing the VS inside a div (inside the container div that is center aligned) with text-align:left;, but that moves the entire div to the side of the container. I have also tried making the div text-align:center; and the VS text-align:left;, but that also moves the entire block all the way to the left. I've also tried the same thing with a table, but no luck.
This is in Firefox by the way. I haven't tested in other browsers, but it needs to work in FF.
Here is pic to show the messed up vertical alignment:

And here is the code for my VS control, without my alignment attempts (if more code is needed, let me know):

  <asp:Label ID="lblStatus" runat="server" ForeColor="Red"></asp:Label>
  <asp:ValidationSummary ID="VS1" runat="server" CssClass="validator" ValidationGroup="theform" />

Could somebody help me vertically align those bullet points in the center of the page?

A: Since bullet points are part of the list items I don't think you will be able to align them. Why not try something like having a top column with 3 divs and place your validationsummary control in the middle one. Try this
HTML Code

            <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="input value" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>

            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Need come input for this" ControlToValidate="TextBox2" Text="*"></asp:RequiredFieldValidator>

            <asp:Button ID="Button1" runat="server" Text="Button" />

            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="please input text" ControlToValidate="TextBox3" Text="*"></asp:RequiredFieldValidator>

            <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Where is the text?" ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator>

            <asp:Button ID="Button2" runat="server" Text="Button" />

CSS
.container
{
    display: block;
    width:800px;
    margin:0px;
    padding:0px;
}

.top
{
    display:inline-block;
    width:800px;
}

.bottom
{
    display:inline-block;
}

.topMiddle
{
    display:inline;
    background-color:Yellow;
    float:left;
    width:300px;
}

.topLeft
{
    display:inline;
    float:left;
    width:250px;
}

.topRight
{
    display:inline;
    float:left;
    width:250px;
}

.bottomLeft
{
    display:inline;
    width:400px;
    float:left;
    background-color:Orange;
}

.bottomRight
{
    display:inline;
    width:400px;
    float:left;
    background-color:Lime;
}

A: Try using this one....

Edit
Set padding left or margin left to ul as you want...
.validator ul { padding-left: 100px; }

A: Hey you may define your parent text-align left center right
according to your design