text:
Q: How to loop through selected elements with document.querySelectorAll I am trying loop on selected elements that queried with document.querySelectorAll, but how?
For example I use:
var checkboxes = document.querySelectorAll('.check');
for( i in checkboxes) {
  console.log(checkboxes[i]);
}

Output:
<input id="check-1" class="check" type="checkbox" name="check">
<input id="check-2" class="check" type="checkbox" name="check">
<input id="check-3" class="check" type="checkbox" name="check">
<input id="check-4" class="check" type="checkbox" name="check">
<input id="check-5" class="check" type="checkbox" name="check">
<input id="check-6" class="check" type="checkbox" name="check">
<input id="check-7" class="check" type="checkbox" name="check">
<input id="check-8" class="check" type="checkbox" name="check">
<input id="check-9" class="check" type="checkbox" name="check">
<input id="check-10" class="check" type="checkbox" name="check" checked="">

10
item()
namedItem()

My problem is that at the end this method returns 3 extra items. How can I properly do it?

A: My favorite is using spread syntax to convert the NodeList to an array and then use forEach for looping.
var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = [...div_list]; // converts NodeList to Array
div_array.forEach(div => {

// do something awesome with each div

});

I code in ES2015 and use Babel.js, so there shouldn't be a browser support issue.

A: for in loop is not recommended for arrays and array-like objects - you see why. There can be more than just number-indexed items, for example the length property or some methods, but for in will loop through all of them. Use either
for (var i = 0, len = checkboxes.length; i < len; i++) {
    //work with checkboxes[i]
}

or
for (var i = 0, element; element = checkboxes[i]; i++) {
    //work with element
}

The second way can't be used if some elements in array can be falsy (not your case), but can be more readable because you don't need to use [] notation everywhere.

A: // for class
for (const elem of document.querySelectorAll('[class=".check"]')){
    //work as per usual
};

// for name
for (const elem of document.querySelectorAll('[name="check"]')){
    //work as per usual
};

// for id
for (const elem of document.querySelectorAll('[id="check-1"]')){
    //work as per usual
};

This provides me with flexibility on what element I would like to work with.

A: It looks like Firefox 50+, Chrome 51+ and Safari 10+ now all support the .forEach function for NodeList objects. Note—.forEach is not supported in Internet Explorer, so consider one of the approaches above or use a polyfill if IE support is required.
https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

const paragraphs = document.querySelectorAll('p');
paragraphs.forEach(p => console.log(p));

paragraph 1

paragraph 2

paragraph 3

paragraph 4

paragraph 5

A: A Main Takeaway:
The type matters.
.map will not work directly on a NodeList but will on an Array.
Compare these:
Array.prototype.map()
NodeList.forEach()
Options:
ES6 available?

*

*The spread operator [...element_list] then Array.map()

*Array.from() on a NodeList.forEach()
ES6 NOT available?

*

*NodeList.forEach()

*A "for loop"

A: With ES6, there is a static method Array.from to take advantages of Array non-static methods (map, filter, ...) :
Array.from(document.querySelectorAll('div')).forEach((element,index) =>
{

     // handle "element"

});

Another use of Array.from since querySelector provides item method:
var all = document.querySelectorAll('div');
// create range [0,1,2,....,all.length-1]
Array.from({length: all.length}, (v, k) => k).forEach((index) => {
     let element = all.item(index);
});

A: A nice alternative is:
[].forEach.call(
    document.querySelectorAll('.check'),
    function (el) {
        console.log(el);
    }
);

but as pointed out, you should use a for loop.

A: For me the most clean and accessible is for of syntax. The second options for me is the spread operator (...) if ES6 is available. Finally, forEach if you are building big app and you want to provide support for most of the browsers out there.

const lis = document.querySelectorAll('li')

let results = {
  'for': [],
  'forEach': [],
  'three-dots': [],
}

// ES6 bellow
for (const li of lis) {
  results['for'].push(li)
}

// ES6 above
[...lis].forEach((li) => results['three-dots'].push(li))

// Most browsers support it
lis.forEach(li => results['forEach'].push(li))

console.log({results})

Item 01

Item 02

Item 03

Item 04

Item 05

Item 06

Item 07

Item 08

A: The shortest and cleanest way to be able to use any regular Array methods, or in your case a for in loop on a NodeList, is to spread it into an array as you fetch it:
const checkboxes = [...document.querySelectorAll('.check')];

for (i in checkboxes) {
  console.log(checkboxes[i]);
}

A: U can select all elements using querySelectorAll method. It will return an array of nodeList.
Lets say u want to select all p tags

paragraph 1

paragraph 2

paragraph 3

paragraph 4

paragraph 5

const paragraphs = document.querySelectorAll('p');

Now the paragraphs has a forEach method which can be used to loop through the nodelist
paragraphs.forEach(console.log); (logs node)


text:
Q: At what version of the SQL standard did arrays appear? There are various versions of the SQL standard: SQL86, SQL89, etc. From what version are arrays defined?
P.S. Please name a full reference book about the SQL standard (including SQL:2011).

A: There is a presentation from Jim Melton from Oracle that summarizes the new things in SQL:1999 and on slide 8, titled "New Data Types" it lists
ARRAY - _datatype ARRAY [n]

so I guess this was introduced in SQL:1999
The filename of the presentation is sql1999_c4.pdf.
I downloaded that ages ago (don't know from where), but searching for it, shows it's still available, e.g. here: https://www.cs.mtsu.edu/~csal/common/cs4560/sql1999_c4.pdf
You can also search for another presentation (which is from IBM) with the filename sql1999_c3.pdf which has also some information about the various versions of the SQL standard.

Nobody is going to give you "a full reference book" because (unfortunately) it is not free and if you want one, you have to pay for it. So giving it away would violate the copyright.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: Chunked uploads via requests in one connection? I'm expecting problems with using requests, i try to send huge file (1GB) via requests, but script that i'm using seems to sending data is trying to upload whole file at once. I tryed to implement 'chunks' but implementing it causes that script uploads files but in multiple connections. (for example 1MB file sends 1MB file but in 1kb parts that causes that script is connecting to the same address 1024 times)
I backuped my old code with tryes upload whole file at once:
with open(local_path, 'rb') as file_obj:
        files = MultipartEncoder({'files[]': (filename, file_obj, 'application/octet-stream')})
        UploadFile = requests.post(self.UploadURL, data=files, headers={'Content-Type': files.content_type}, stream=True)

How to upload whole file, but sended in 1MB chunks, in one connection?
I mean:

-Python is reading file (in 1MB parts)
-Python opens post connection
-Python sends 1MB part
-Python waiting to part being sended
-Python is reading file (in 1MB parts)
-Python sends 1MB part
...


text:
Q: Gitlab Ngix redirect to other server/page I am hosting a gitlab server with the omnibus pack.
The url is something like http://myurl.com/gitlab
I need/want to add a redirect to so:
http:/myurl.com/jsp

will redirect to a tomcat server I have on the local network.
Google told me I could do this by using custom nginx strings/confs enabled and write a serverblock or something like that. (Other ideas are also welcome :) )
What would be your configuration?

A: You should be able to add a rule for /jsp (similar to this article) to your existing server section in the nginx configuration file:
    location /jsp {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto https;
        proxy_redirect off;
        proxy_connect_timeout      240;
        proxy_send_timeout         240;
        proxy_read_timeout         240;
        # note, there is not SSL here! plain HTTP is used
        proxy_pass http://tomcat_server;
    }

A: I would insert a reverse proxy in front of your Gitlab instance to ensure that your intention survives code updates. This can be NGINX, Apache, or HAProxy.


text:
Q: How to unbind or turn off all jquery function? I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];

        function replacePage(url) {

            var loading = '

'
            $('.content').fadeOut(200);
            $('.container').append(loading);

            $.each( requests, function( i, v ){
                v.abort();
            });

            requests.push( $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "html",
                    success: function(data){

                        var dom = $(data);
                        //var title = dom.filter('title').text();
                        var html = dom.find('.content').html();
                        //alert(html);
                        //alert("OK");
                        //$('title').text(title);
                        $('a').off();
                        $('.push-load').remove();
                        $('.content').html(html).fadeIn(200);
                        //console.log(data);

                        $('.page-loader').hide();
                        $('.load-a').fadeIn(300);
                    }
                })
            );
        }

        $(window).bind('popstate', function(){
            replacePage(location.pathname);
        });

Thanks in advance!

A: simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});

or
used
 $('#id').unbind();

A: Try this,
 var requests = [];

   function replacePage(url) {
       var obj = $(this);
       obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
       var loading = '

';
        $('.content').fadeOut(200);
        $('.container').append(loading);
       $.each(requests, function (i, v) {
           v.abort();
       });
       requests.push(
       $.ajax({
           type: "GET",
           url: url,
           dataType: "html",
           success: function (data) {
               var dom = $(data);
                    //var title = dom.filter('title').text();
                    var html = dom.find('.content').html();
                    //alert(html);
                    //alert("OK");
                    //$('title').text(title);
                obj.bind("click", replacePage); // binding after successfulurl ajax request
                 $('.push-load').remove();
                    $('.content').html(html).fadeIn(200);
                    //console.log(data);

                    $('.page-loader').hide();
                    $('.load-a').fadeIn(300);
            }
       }));
   }

Hope this helps,Thank  you


text:
Q: Is my relation a one-to-many or a many-to-many? I have a model called Addresss which as the name sounds, is a list of addresses.
These addresses can belong to a Client and a client can have many of these addresses.
To link these addresses to the client, I will simply have a table called ClientAddress with 3 columns: id, client_id and address_id.
Is this an example of a one to many or a many-to-many relationship? I currently have it setup as a ManyToMany relationship in Phalcon however I'm not sure if it should actually be One to Many.

A: It's a one-to-many relation. One client (can) have multiple addresses. One address belongs to only one client.
Regarding your clientAddress table, I'd get rid off it as you can store the client id on the adress table.
If, as your tags suggest you're using phalcon and decide do go with phalcon's orm you should have a look at the documentation : Working with Models

A: Its all depends how you are thinking about your Entities
Lets start from Client
We would like to store information about Client. Now if our Client has only one specific Location then we have two options. We can directly store the Address information in same table as-
clients table
id, f_name, l_name, address, current_city, home_city, etc....
In this case there is nothing about Relation
If you are interested then you can split this table and store Location information on other table which you may name as addresses. Then the Relation between Client and Address will be one-to-one relation.
Now, if our Client has different office on different Location then it is mandatory to store Location information on different table. Then the Relation will be one-to-many as our Client has different `Location'.
Now, if we have many Client on same Location (same building may be) and our Client has many office in many Location then it will be as many-to-many relation. As Client hasMany Address and Address hasMany Client we new a pivot or intermediate table to hold our Relation information.

A: It depends on quite how complex your model is likely to become.
Suppose your "clients" are branches of a national company. Eech "client" may then have multiple adrresses - delivery address and billing address for instance. And equally, since the accounts-payable function may be centralised to either a regional or national branch (which may itself have, or not have a "delivery address)" the billing address is likely to be shared amongst many "clients."
So, in this scenario, many-to-many.


text:
Q: Android Studio errors once detached from EXPO I've been using Expo XDE and once I detach the project and run in Android Studio I'm having some major problems and can't sort it out.
Env Details:
Windows: 10
Android Studio: 3.1.4
Node.js: 8.11.3
NPM: 5.6.0
expo: 1.1.0-beta.5
exp: 57.0.0
Steps to replicate issue
Open upe Expo XDE and create new project
-> Run and test that it works in simulator in android studio (yes it works)
Open up app.json and add
"android": {
"package": "com.yourcompany.yourappname"
}

cmd line into project and 'exp detach'
'exp start' (no errors given initially and gives url)
Open project in Android Studio (takes time with "Building 'android' Gradle project info")
Build completes successfully with all oks.
Now in android studio I go to Run on the top menu, then select Run 'app'
emulator screen goes white doesnt change and under the Run output I get these errors
(Also once all this was done I looked back in the cm line where I ran exp start and it now says "Metro Bundler failed to start. (code: EPERM)")
E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: 33, errorType: GraphMethodException, errorMessage: Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api}
W/AsyncCondition: Could not find listener for key: openOptimisticExperienceActivity
Could not find listener for key: openExperienceActivity
E/AppLoader: Error fetching cached manifest, falling back to default timeout: Could not load manifest. Are you sure this experience has been published?
D/AndroidRuntime: Shutting down VM

              --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yourcompany.tes, PID: 7527
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yourcompany.tes/host.exp.exponent.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at host.exp.exponent.ExponentManifest.fetchCachedManifest(ExponentManifest.java:287)
at host.exp.exponent.AppLoader.start(AppLoader.java:91)
at host.exp.exponent.experience.DetachActivity.onCreate(DetachActivity.java:95)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 7527 SIG: 9
Application terminated.


text:
Q: Erase a 1st gen iPad I have a 1st gen iPad that I don't know the passcode for. iTunes tells me that I need to enter the passcode before I can use it with iTunes.
So I followed some instructions and put the iPad into Recovery mode, which let me connect to iTunes and hit the Restore button.
iTunes apparently will not let me just restore the iPad using the iOS version it currently has; instead it demands that I let it download a new iOS version first.
But my internet is so slow and unreliable where I live now that I have not been able to get iTunes to finish downloading.
So I found a website that lets you download IPSW's.  I downloaded 5.1 for iPad 1st gen. I then held Option while clicking Restore in iTunes, chose this IPSW file, and iTunes told me it is not valid.
So....
Questions:

*

*Is there any way I can use this iPad as-is without knowing the passcode?

*Is there any way I can restore it without downloading any huge IPSW files?

*If not, is there any other way I can get rid of the passcode or wipe the device clean?

*I welome jailbreaking and 3rd-party software in my quest...

A: The iPad 1 should be good to go for a valid version of 5.1.1

*

*http://www.icj.me/ios/all#iPad11
I'd say the easiest thing to do would be to take the iPad to a copy of iTunes that has a good internet connection or download a reputable copy (for whatever reputable means to you) of 5.1.1 IPSW and use your iTunes to wipe and restore the iPad.
Jailbreaking might be an option, but I'd go with easy.

A: Enter the wrong passcode 10 times to erase the device. Later in the process, like after try 6 the wait starts to get longer before it will let you try again. After erasing the device you will be able to set it up with your Apple ID.


text:
Q: python array to string but with commas on every string return I have a array something like this
my_array = ['MY_INVOICE', 'YOUR_INVOICE']

and when I convert it to a string using like this
final_string +=  ','.join(my_array)

it is giving something like this
MY_INVOICE,YOUR_INVOICE

while I want something like this
"MY_INVOICE", "YOUR_INVOICE"  (like with commas on it) tried few solutions but not  working

A: Here's what I think you're looking for.
my_array = ['MY_INVOICE', 'YOUR_INVOICE']
print('"' + '", "'.join(my_array) + '"')

Result:
"MY_INVOICE", "YOUR_INVOICE"

A: May be :
final_string +=  '"' + '", "'.join(my_array) + '"'

A: You could do something like this:
my_array = ['MY_INVOICE', 'YOUR_INVOICE']
my_array[0] = '"' + my_array[0] # Adding opening double quotes to the first value
my_array[-1] = my_array[-1] + '"' # Adding closing double quotes to the last value
print('", "'.join(my_array)) # Joining with quotes and comma with space

A: Try:

my_array = ['MY_INVOICE', 'YOUR_INVOICE']

final_string = ''

final_string +=  '\"' +'\", \"'.join(my_array) + '\"'

print(final_string)

wich outputs: "MY_INVOICE", "YOUR_INVOICE"

A: To turn this list…
my_array = ['MY_INVOICE', 'YOUR_INVOICE']

…into this string:
"MY_INVOICE", "YOUR_INVOICE"

You could do this:
new_str = ', '.join(f'"{word}"' for word in my_array)

Explanation:
f'"{word}"' takes word and puts double-quotes around it - if word was Apple it becomes "Apple"
f'"{word}"' for word in my_array does this for each word in my_array
', '.join(...) joins together the pieces with ,  in between

A: I solved your problem by trying to change your code as less as possible. This is my solution which works fine, even though I don't really know why you would do something like this.
Anyway that's not my problem.
my_array = ['MY_INVOICE', 'YOUR_INVOICE']
my_array = (f"\"{element}\"" for element in my_array)
final_string = ""
final_string +=  ','.join(my_array)

This is the output:
"MY_INVOICE","YOUR_INVOICE"

A:
while I want something like this
"MY_INVOICE", "YOUR_INVOICE" (like with commas on it)

I think you mean quotes ("), not commas (,) which your original version already has.
You need to add the quotes yourself. One way is with a generator expression:
final_string +=  ', '.join('"' + w + '"' for w in my_array)

Here I add the quotes around each word before joining them together with commas.


text:
Q: java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V 04-Feb-2020 18:25:39.794 INFO [localhost-startStop-1] org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6e2af876: defining beans [sessionFactory,sessionFactoryCCA,sessionFactorySSO,login,internalUsersMgmt,rolesMgmt,sessionManager,productManager,birtManager,templateManager,reportFileManager,dashboardDetailsDAO,configDynamicFilterDAO,oAMDataDAO,scheduledFileManager,cronTrigger,loginDAO,internalUsersDAO,applicationResourceDAO,reportTemplateStoreDAO,reportFileStoreDAO,scheduledFileStoreDAO,templateSchedulingParamDAO,reportUtilsDAO,rolesDAO,myFilter,userMasterDAO,userRoleDAO,sessionServiceDAO,permissionDAO,roleMenuDAO,rolePermissionDAO,ssoManagerDAO]; root of factory hierarchy
04-Feb-2020 18:25:39.794 SEVERE [localhost-startStop-1] org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
        at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:272)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:196)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4699)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5165)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:970)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1841)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
        at net.sf.cglib.core.ClassEmitter.begin_class(ClassEmitter.java:77)
        at net.sf.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:173)
        at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
        at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:215)
        at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
        at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117)
        at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
        at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
        at org.hibernate.impl.SessionFactoryImpl.<clinit>(SessionFactoryImpl.java:321)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
        at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:855)
        at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:774)
        at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
        ... 25 more
04-Feb-2020 18:25:39.805 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
04-Feb-2020 18:25:39.889 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Context [/omega] startup failed due to previous errors
04-Feb-2020 18:25:39.922 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [omega] registered the JDBC driver [org.apache.derby.jdbc.AutoloadedDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
04-Feb-2020 18:25:39.923 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [omega] registered the JDBC driver [oracle.jdbc.OracleDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
04-Feb-2020 18:25:39.923 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [omega] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
04-Feb-2020 18:25:39.933 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [omega] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)` `
 java.lang.Object.wait(Object.java:503)
 java.util.TimerThread.mainLoop(Timer.java:526)
 java.util.TimerThread.run(Timer.java:505)` `


text:
Q: Indexed replacement Is there some equivalence of MapIndexed for rules?
Consider a substitution on
3 a + 4 b + 21 c + ....

The first integer I want to replace by 1, the second integer by 4, and the i'th integer by i^2.
1 a + 4 b + 9 c  + ....

How would you do that?
I imagine some kind of indexed replacement would be useful.
Addition:I would like to use it to replace expressions like f[a]@f[b]@f[c]@...@f[X] with f[1]@f[2]@f[3]@...@f[n]

A: If we assume that the integers that you wish to replace are on the first level as in the example, then a good equivalent for MapIndexed is... MapIndexed!  The second argument does not need to be a list:
$eqn = 3 a + 4 b + 21 c;

MapIndexed[#1 /. _Integer :> #2[[1]]^2 &, $eqn]

(* a + 4 b + 9 c *)

A: Here's an approach that uses a more explicit rule replacement:
MapIndexed[{##} /.
   {coeff_ sym_ | sym_, {index_}} :> index^2 sym &,
 expr]

A: Though it is not purely functional I often find it easiest to simply use a temporary variable for incrementing in a replacement:
Module[{i = 1},
 3 a + 4 b + 21 c /. n_Integer :> i++^2
]

a + 4 b + 9 c

A couple of answers are assuming that you want to increment the counter for each object at level one, rather than for each appearance of an integer.  This is an important distinction.  Consider:
expr = 3 a^2 + b + 21 c;

Module[{i = 1}, expr /. n_Integer :> i++^2]

a^4 + b + 9 c

If instead you prefer operate on coefficients including the implicit 1 for b you might consider tools like CoefficientRules for your manipulation:
CoefficientRules[expr]

MapIndexed[# -> #2[[1]]^2 &, %[[All, 1]]]

FromCoefficientRules[%, Variables@expr]

{{2, 0, 0} -> 3, {0, 1, 0} -> 1, {0, 0, 1} -> 21}

{{2, 0, 0} -> 1, {0, 1, 0} -> 4, {0, 0, 1} -> 9}

a^2 + 4 b + 9 c

A: Ah well, watch dis (which will end in tears if you do not provide the structure mentioned by @R.M):
i = 1;
3 a + 4 b + 21 c + 30 d + 15 e /. Times[a_, b_] :> (i++)^2 b

a + 4 b + 9 c + 16 d + 25 e

Regarding your additional request:
i = 1;
f[a]@f[b]@f[c]@f[d] /. f[a_] :> f[i++]

f[1][f[2][f[3][f[4]]]]

A: Assuming your expression is of the form given in the question and that it is ordered in the sense of OrderedQ, then a simple way to replace the numbers would be:
Dot[Range[Length@#]^2, #] &@Last@GatherBy[Level[3 a + 4 b + 21 c, {-1}], Head]
(* a + 4 b + 9 c *)

To break it down further, Level[3 a + 4 b + 21 c, {-1}] gives you the leaves of the expression (or loosely speaking, the individual components sans the head), which is {3, a, 4, b, 21, c}. Then it is collected according to their heads using GatherBy, and Integer comes before Symbol. Finally, the integers are discarded and replaced with the square of the indices and then the expression is reconstructed.

A: Range[ Length @ #]^2 . Last /@ List @@ # &[3 a + 4 b + 21 c + 30 d + 15 e]

a + 4 b + 9 c + 16 d + 25 e

or
List @@ #[[All, 2]].(Range @ Length @ #)^2 & [ 3 a + 4 b + 21 c + 30 d + 15 e]

A: Here is a simple approach,
index = 0
1 a + 2 b + 4 c + 10 f /.  b_?IntegerQ :> (++index)^2

Unlikely to do as you expect, but I'll mention it as it does work in some situations.
Note for one thing you lose the '1' as it is simplified out before substitution


text:
Q: Show that a nonabelian group of ordr p^n has an automorphism of order p. I am not sure how to prove this question: "Show that a nonabelian group of order p^n has an automorphism of order p". I found a proof of Wolfgang Gaschütz that if G is a finite non-abelian p-group, then G has an automorphism of p-power order which is not inner. However, this proof is too long, and I have a feeling that this should be a fact easy to prove. Is there any better way to do it?
Thanks

A: Well, the complete solution's been given by Oblomov+Yazdegerd in the comments, so I only post it as "answer" to try to save this question from the non-answered questions hell:
Let $\,G\,$ be a non abelian finite $\,p-$group, say $\,|G|=p^n\;$ , then:
$$\begin{align*}\bullet&\;\;\;1<|Z(G)|<p^n\\
\bullet&\;\;\;\text{Inn}\,(G)\cong G/Z(G)\;\;\text{and this last group cannot be cyclic non-trivial, thus}\\
\bullet&\;\;\;|\text{Inn}\,(G)|=p^k\;,\;\;1<k<n\\
\bullet&\;\;\;\text{By Cauchy's theorem there exists an element of order $\,p\,$ in}\;\;\text{Inn}\,(G)\le\text{Aut}\,(G)\end{align*}$$


text:
Q: Best practices for "connecting" two separate react apps Lets say we have two react apps. And we want to connect them. By "connect" I mean passing data from one to the other.
One option would be to export the Main component of the 2nd app and include it as a submodule and then import it in the 1st app and define our router like
import SecondApp from 'secondApp';
    ...
    <Provider store={ store }>
        <Router history={ appHistory }>
            <Route path='/' component={ FirstApp } />
            <Route data={ someData } path='/pathb' component={ SecondApp } />
        </Router>
    </Provider>

Another option will be to not have it as a submodule but deploy it separately (so it will make the deployments easier) and require the data from the server.
Another option will be to deploy it separately but pass the data through the localStorage.
Probably there more options, but which are the best practices (if any) and why?


text:
Q: Name server configuration issues I know this is a bit of an odd request but it is all Google's fault... So that being said I'm a university student and I have my own website for the purpose of marketing my self to potential employers for co-op.
Okay, the actually question is: I set my MX record using 1&1's name server to point to Google apps however I never bothered to set up a webserver, just mail. Now I need an actually website as interviews start soon but every host wants me to point to their name servers, the only problem being the moment my MX record switches Google apps will stop my account and mail services and I can't re register because Google apps is now only for enterprise customers and I just love gmail too much to risk losing it. So, is there any way I can determine the IP address the host is using and point my website too it, like in CPANEL? or do I absolutely have to use their name server... I'm tempted to just set up an old PC with webmin in my father's basement if I can't find a way to point directly to an IP.
Thanks so much for any help!

A: Why not just use 1&1 hosting too?
They provide Windows and Linux Hosting
If you aren't willing to do that, call up your hosting support. They should be able to determine the IP address you will need for you A Record.
More on A Records


text:
Q: Html search form response to php array I am trying to make a search form working but i cannot due my lack of knowledge.
The form has 3 fields ( select with values from 1-5 )

Field 1: Rooms, Field 2: Adults, Field 3: Childs;

I need to translate the responde from form into php array:
The response should be as example if i select 1 room and 2 adults:
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"));

I use the below code
$AdultsNO = intval($_POST["AdultsNO"]);
$RoomsNO= intval($_POST["RoomsNO"]);
$rooms = array();
for ($x = 0; $x < $RoomsNO; $x++) {
if ( count($RoomsNO) > 0)
    array_push($rooms,array("paxType" => "Adult"));
}

But is returning the response an adult on each room:

for example :
if i select 1 room and 2 adults i get the response for 1 room and 1
  adult
if i select 2 room and 4 adults i get the response for 2 room
  each room with 1 adult

Or to make it easier:
Please advise me how to create a rule as below: ( count if two or more conditions are true
    if ( count($RoomsNO) = 1) and ( count($Adults) = 1)
        array_push($rooms,array("paxType" => "Adult"));
and

   if ( count($RoomsNO) = 1) and ( count($Adults) = 2)
        array_push($rooms,array("paxType" => "Adult"), array("paxType" => "Adult"));
and
  if ( count($RoomsNO) = 2) and ( count($Adults) = 4)
        array_push($rooms,array("paxType" => "Adult"), array("paxType" => "Adult"));
        array_push($rooms,array("paxType" => "Adult"), array("paxType" => "Adult"));

Please let me know if you need any other information.


text:
Q: Can I use Firebase Cloud Functions & Firestore as a cache server? I want to make an Android app.
It uses some rest api. (The Rest API is not mine, external 3rd party server)
But the provider restricts the api, 20 request per 1 second.
In my case, it is too short.
So I want to cache the data in my backend.
And I want to make my backend using Firebase.

*

*Firebase cloud function should be run always and it request the rest api instead of user (20 request per 1 second)

*It stores the response in the Firestore or Realtime database (Firebase).
Step 2 has no problem.
But I don't know whether step1 is possible or not.
Generally, cloud function is used as a trigger.
But in my case I want to use it like a crawler(?).
It should always run without any trigger.
I knew it is not free, It is for paid service.
Is it possible?
Are there anything what I am missing?

A: You can access/trigger your cloud function via a http GET.
Your function that, can query the database and make a lookup, if it needs
to refresh it's data in the database.
If so, it queries your restricted rest api, stores the result into your database and returns then the output as the result of your GET request.


text:
Q: VB.NET Track COM RCW error I have a really big project that I can not easily strip down.
When the application is being closed, I get the error
"InvalidComObjectException: A COM object that has been disconnected from the RCW can not be used."

Details:
System.Runtime.InteropServices.InvalidComObjectException has occured.
  HResult=-2146233049
  Message=A COM object that has been disconnected from its RCW can not be used.
  Source=mscorlib
  StackTrace:
       at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis)
  InnerException:

Unfortunately I can not see what COM object this is about.
Does anybody know how I can find that out? Unfortunately I can't read ASM to analyze the disassembly.

A: There are some steps you could try and since you haven't posted any code I will try to enumerate some of the most common key factors...
First, there is no order when disposing objects. If a close/dispose/finalize action is invoked, object C might be disposed before object A and if some object is still alive it might try to access an already disposed object.
Second, beware of events. It's very common to get errors about accessing a disposed object originated from an event call.
Third, do not dispose objects inside an event scope nor destructors. Create your own method to free your object(s).
Since you don't know which COM object is the culprit, I suggest you look for the ones that you do close, dispose, disconnect, etc...
You might want to read this blog in order to better understand how RCW's work and also to help you with your problem.
Edit:
After reading your comment, I felt I should add two possible causes:

*

*If after removing Microsoft.VisualBasic runtime methods you've solved your problem, then I suspect that inside one, or more, of those methods you have incremented the count of a reference to one, or more,  of your COM(s) and did not release properly.
Be sure to ReleaseComObject checking the reference count until it's 0 and then set it to nothing(VB) or null(C#) and let the Garbage Collector do the rest.

*The other option is that one of those methods tried to access an already disposed reference to a COM object, resulting in a RCW error, since is no longer callable.
As a final comment, after releasing the COM object always set it to nothing or null, this will release the reference to the variable and you can always check it's availability anywhere in the code.


text:
Q: Format Phone Number inside of concat field SQL I have a unique circumstance here. I have a concatenated field I call address and as part of this address I have the phone number of that address on the last line. currently the phone number is formatted like:
8885551212

I want it to format like:
(888) 555-1212

Below is my INSERT into my temp table that I do for getting everything correct. Any guidance on how to get the phone portion working right is a great help. I did find one article talking about using a function but I am unsure how to write it up properly for my circumstance. Thank you.
INSERT into #Referral_Temp (status, physician, timeFrame, date, address)
    select o.actStatus, o.actTextDisplay, apptTimeframe, apptDate,
    (select (p.address_line_1 + CHAR(13)+CHAR(10) + p.address_line_2 + CHAR(13)+CHAR(10)
             + p.city + ', ' + p.state + ' ' + p.zip + CHAR(13)+CHAR(10) + p.phone)
             AS address)
    from order_ o
    join provider_mstr p on o.refer_to_prov_id = p.provider_id
    where o.encounterID = @enc_id

A: Use Stuff string function to insert the required special into the string. Try this.
SELECT '('+ Stuff(Stuff('8885551212', 4, 0, ') '), 9, 0, '-')

A: You can use the SUBSTRING function:
change
+ p.phone

to
+ '(' + SUBSTRING(p.phone,1,3) + ') '
+ SUBSTRING(p.phone,4,3) + '-'
+ SUBSTRING(p.phone,7,4)

A: Try this
SELECT '(' + SUBSTRING('8885551212',1,3) + ') ' + SUBSTRING('8885551212',4,3) + '-' + SUBSTRING('8885551212',7,4)

Output will be :- (888) 555-1212


text:
Q: SQL Server : function to display previous Friday's date if @date is not a Friday I am a newbie to advanced SQL, I need to write a SVF in SQL Server to return previous Friday's date if the parameter date I entered is not a Friday.
For example, today is Wednesday, 7/1/2015, this function should return previous Friday 6/26/2015. Suppose today is Friday 7/3/2015, then the function will return 7/3/2015 (no change).
Ask for help if you can edit my following code:
CREATE FUNCTION fnDateCheck (@date datetime)
RETURNS @FridayDate date
AS
BEGIN
    DECLARE @FridayDate

    if
        RETURN

    else if
        RETURN

END
GO

I found this reference post, quite similar to what I am asking but it's not a function: Get last Friday's Date unless today is Friday using T-SQL
declare @date datetime;
set @date = '2012-08-10'

SELECT
    CASE WHEN datepart(weekday, @date) > 5
           THEN DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0))
         ELSE DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0))
    END

Thanks so much!!

A: CREATE FUNCTION fnDateCheck (@date datetime)
RETURNS datetime
AS
BEGIN
   DECLARE @FridayDate DATETIME;

IF (DATEPART(WEEKDAY, @date ) <> 6)
   BEGIN
        SELECT @FridayDate = case when datepart(weekday, @date) >5 then
        DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0))
        else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0)) end
   END
ELSE
   BEGIN
     SET @FridayDate = @date
    END

 RETURN @FridayDate;

END
GO

A: Seems something like this would help you might need to reformat and obviously this isn't a whole function, but the part that does the logic.
SELECT case
    when datepart(dw,getdate()) != 6 then DATEADD(wk,DATEDIFF(wk,7,GETDATE()),4)
    else GETDATE()
end

A: The script you found works fine. You just need to write it into a function.
CREATE FUNCTION fnDateCheck
(
    @date datetime
)
RETURNS DATETIME
AS
    BEGIN
        RETURN (SELECT CASE
            WHEN DATEPART(WEEKDAY, @date) > 5 THEN
                DATEADD(DAY, + 4, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0))
            ELSE
                DATEADD(DAY, - 3, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0))
        END)
    END
GO


text:
Q: Sum of floors inequality I'm trying to show the following inequality, for $x\geq0$:
$$
\lfloor30x\rfloor+\lfloor x\rfloor\geq\lfloor15x\rfloor+\lfloor10x\rfloor+\lfloor6x\rfloor.
$$
Intuitively this statement looks like it should be true because the LHS has two terms and the RHS has three terms - but I don't know how to formalize it. I am aware that $\lfloor a\rfloor+\lfloor b\rfloor\leq \lfloor a+b\rfloor$, but I don't know I can directly apply that here. Any help would be appreciated!

A: Let $x=A+a,6x=B+b,10x=C+c,15x=D+d,30x=E+e$ where big letter is the integer part and small letter is the decimal part.
(1) If $a<{1\over30}$ we have $$b=6a\implies B=6A$$ $$c=10a\implies C=10A$$ and so on $D=15A,E=30A$. So $A+E=B+C+D$.
(2) If ${1\over30}\leq a<{1\over 15}$ then we have $B=6A,C=10A,D=15A$ $$e=30a-1\implies E=30A+1$$ so $A+E>B+C+D$
(3) If ${1\over 15}\leq a<{1\over 10}$ then we have $B=6A,C=10A$ $$d=15a-1\implies D=15A+1$$ $$e=30a-2\implies E=30A+2$$ so $A+E>B+C+D$
Can you finish off the remaining two cases?

A: I have a quite tedious argument that this inequality holds:
Firstly, by taking $x \pmod 1$ we may assume $x \in [0,1)$. Let $k$ be the greatest integer, such that $\frac{k}{30} \leqslant x$ (so $k = \lfloor 30x \rfloor$). Then we would want to prove that
$$\lfloor 15x \rfloor = \bigg \lfloor \frac{k}{2} \bigg \rfloor.$$
Firstly, $\lfloor 15x \rfloor \geqslant \big\lfloor \frac{k}{2} \big\rfloor$, as $15x \geqslant \frac{k}{2}$. Suppose $\lfloor 15x \rfloor > \big\lfloor \frac{k}{2} \big\rfloor$, then we can choose an integer $l$ such that $15x \geqslant l > \frac{k}{2}$. But that would mean $\frac{2l}{30} \leqslant x$ and $2l > k$, which is a contradiction with a definition of $k$.
Using the same methods, we can transform our inequality to
$$ k+ \bigg\lfloor \frac{k}{30} \bigg\rfloor  \geqslant \bigg\lfloor \frac{k}{2} \bigg\rfloor + \bigg\lfloor \frac{k}{3} \bigg\rfloor + \bigg\lfloor \frac{k}{5} \bigg\rfloor $$
where $k$ is an integer between 0 and 29. That's $30$ cases to check, but they're all simple so it can be done quite quickly.
EDIT We can also transform RHS using $\lfloor a \rfloor + \lfloor b \rfloor \leqslant \lfloor a+b \rfloor$. Then we will obtain inequality $k + \big\lfloor \frac{k}{30} \big\rfloor  \geqslant \big\lfloor \frac{31k}{30} \big\rfloor$, which is not true in general case, but it holds for $k=0,\ 1,\ldots,29$.


text:
Q: How to mask an image in IOS sdk? I want to apply an image filter or mask when a word drawn on the image.The word will have transparent effect to see through the background image.
Is it possible in native IOS sdk or i need different api to perform this.
This image consist of 2 images. one is where India is written over, and another one is which is see through India letter.
This is the code i am using to generate image from text.
-(UIImage *)imageFromText:(NSString *)text{
// set the font type and size
UIFont *font = [UIFont systemFontOfSize:100.0];
CGSize size  = [text sizeWithFont:font];

// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
    // iOS is < 4.0
    UIGraphicsBeginImageContext(size);

// optional: add a shadow, to avoid clipping the shadow you should make the context size bigger
//
 CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetShadowWithColor(ctx, CGSizeMake(0.0, 1.0), 5.0, [[UIColor blackColor] CGColor]);
CGContextSetBlendMode(ctx,kCGBlendModeNormal);
CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);

/*NSLog(@"Rect  %@",CGContextGetClipBoundingBox(ctx));
CGImageRef alphaMask = CGBitmapContextCreateImage(ctx);
CGContextClipToMask(ctx, CGContextGetClipBoundingBox(ctx), alphaMask);*/

// draw in context, you can use also drawInRect:withFont:
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];

// transfer image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;}

It is working fine, however i need to generate the image which will have black background and transparent text to see through it.

A: You can use this code(got from here),
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage;

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    return [UIImage imageWithCGImage:masked];

}


text:
Q: Go to a new html file depending on time of day I'm very new to JavaScript so I wondered if any of you could solve this puzzle. This is obviously completely wrong but hopefully you see what I need.
I need the index.html to redirect to a new .html file depending on time of day.
function getIndex() {
var currentTime = new Date().getHours();
if (0 <= currentTime&&currentTime < 5) {
document.write("night.html");
}
if (5 <= currentTime&&currentTime < 11) {
document.write("morning.html");
}
if (11 <= currentTime&&currentTime < 16) {
document.write("day.html");
}
if (16 <= currentTime&&currentTime < 22) {
document.write("evening.html");
}
if (22 <= currentTime&&currentTime <= 24) {
document.write("night.html");
}
}

getIndex();

A: Here is another way of going about things.
function getIndex() {
    var d = new Date();
    var h = d.getHours();

    var pages = ['night', 'morning', 'day', 'evening', 'night'];
    var eTimes = [0, 5, 11, 16, 22, 24];

    for (var i = 0; i < eTimes.length - 1; i++) {
        if (eTimes[i] <= h && h < eTimes[i + 1]) {
            window.location.href = pages[i] + '.html';
        }
    }
}

getIndex();

A: You just need to redirect page using window.location.href
function getIndex() {
  var currentTime = new Date().getHours();
  if (0 <= currentTime&&currentTime < 5) {
      window.location.href = 'night.html';
  } else if (5 <= currentTime&&currentTime < 11) {
      window.location.href = 'morning.html';
  } else if (11 <= currentTime&&currentTime < 16) {
     window.location.href = 'day.html';
  } else if (16 <= currentTime&&currentTime < 22) {
    window.location.href = 'evening.html';
  } else if (22 <= currentTime&&currentTime <= 24) {
    window.location.href = 'night.html';
  }
}

getIndex();

Rest all you code is fine


text:
Q: Regex and Autohotkey - extract pdf name and page number from query string I handle many documents on a day to day basis and was using regular expression and Autohotkey to open a particular page of pdf from a given string.  For ex, I will copy the below string including the parenthesis and press a hotkey
(16G3537-2011 tax return-page 25)
Any my below Ahk code would open the 25th page in the pdf 16G3537-2011 tax
RegExMatch(clipboard,"i)\((.*)\s*-page\s*(\d+)\)",part)
Run, %Adobelocation% /A page=%part2% %copyz%/%part1%.pdf"

Adobelocation is the location of adobe reader in my computer
copyz is the location of folder where the pdf is located
I know AHK to some extent, but have difficulty with regular exp.  Now my query string has been modified to just
16G3537-2011 tax return.pdf_pages 25
I am really at a loss to make my code open the 25th page using the modified string.  Kindly help me.
Edit:
The command line for this code is
Run, pathto\Acrobat.exe /A "page=" part2 " C:\folder\" part1 ".pdf"

A: Try
RegExMatch(clipboard,"i)(.*)\s*\.pdf_pages\s*(\d+)",part)
Run, %Adobelocation% /A page=%part2% %copyz%/%part1%.pdf"

The difference to the original regex is the Elimination of the parenthesis matching (\(, \)) and the Substitution of the separator Char in Front of the page specific (\. instead of -).
Note That since the parentheses around the file name have been dropped, you'd need some other Marker to indicate the Start of the relevant expression if you'd Extract from embedding Text. The context you give suggests that this is not necessary in your Case ( the clipboard containing only the relevant data), but keep it in mind when reusing the regex.
Still wondering why return would not be Part of the extracted file name, but you Write that the original Works so i let this Aspect Rest.


text:
Q: getting "android.content.res.resources$notfoundexception" I have 3 tabs and each tab has got a listview. I have registered these listviews for contextual menu. I have three different arraylists in which i store the items for respective listviews.
now i want the position of the item of listview which was clicked.
my code is :
public boolean onContextItemSelected(MenuItem item) {

     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

      switch(item.getItemId()){

   case R.id.mycards_contextmenu_1:

       if(mCurrentTab.equals("Tab 1")){
           try{
           int pos= info.position;
           Toast.makeText(getBaseContext(), pos, Toast.LENGTH_LONG).show();
           }catch(Exception e){
               Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
           }
           }
    break;

  }

i am getting
   android.content.res.resources$notfoundexception

where have I gone wrong?
EDIT:
Stack Trace :

 03-14 22:06:12.488: E/AndroidRuntime(3055): FATAL EXCEPTION: main
 03-14 22:06:12.488: E/AndroidRuntime(3055): android.content.res.Resources$NotFoundException: String resource ID #0x0
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.content.res.Resources.getText(Resources.java:229)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.widget.Toast.makeText(Toast.java:265)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at neeraj.cardXchange.myCardsPackage.myCardsActivity.onContextItemSelected(myCardsActivity.java:211)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.app.Activity.onMenuItemSelected(Activity.java:2552)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3601)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:924)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.widget.AbsListView$1.run(AbsListView.java:3529)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.os.Handler.handleCallback(Handler.java:615)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.os.Handler.dispatchMessage(Handler.java:92)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.os.Looper.loop(Looper.java:137)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at android.app.ActivityThread.main(ActivityThread.java:4745)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at java.lang.reflect.Method.invokeNative(Native Method)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at java.lang.reflect.Method.invoke(Method.java:511)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 03-14 22:06:12.488: E/AndroidRuntime(3055):    at dalvik.system.NativeStart.main(Native Method)

A: Toast.makeText(getBaseContext(), pos, Toast.LENGTH_LONG).show();

should be
Toast.makeText(getBaseContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();

Toast also has a makeText() method that accepts in a String resource id (which is an int), and by pasing pos, you call that method, which can't find a String resource with that id, hence the
android.content.res.Resources$NotFoundException


text:
Q: htaccess SetEnvIf true If I want to set an environment variable before RewriteRules are evaluated, I have to use SetEnvIf instead of SetEnv. However, SetEnvIf requires one to have a condition. As it is, I have:
SetEnvIf Request_Method ^ ENV=VALUE

Is there a better way to do this?

A: You can use mod_rewrite's E flag:
RewriteRule ^ - [E=ENV:VALUE]

Which will guarantee that it gets set before (or after) rules get applied.

A: Using SetEnvIf you can do something like:
SetEnvIf ENV  ^(.*)$ ENV=VALUE


text:
Q: Inserting a comment in docx file using python 3 I'm trying to write an application that scans a word .docx file and offers suggestions. I want to ideally put the suggestions on the document itself using MS Word's annotation functionality. (Here is an image of what I'm talking about if i'm not being clear -
MS Word Annotation Functionality
My question is how do I achieve this in Python. I looked through Python-docx's functionality, but didn't find anything there.
Alternatively, I was thinking of manually doing it, where I'd programmatically go into the docx file, go into the xml file, and add the comment that way but I'm not sure how to approach this and I'm not sure if there is a better way to do it.
Please advise :)
Appreciate the help in advance!

A: for anyone else looking, this is a fork from python-docx that implements comment functionality.


text:
Q: Interpret RTF on server and echo the result in HTML tags, re-using bold, italic, ul and lists I've been crawling the web for days now and couldn't find exactly what I'm looking for. So hopefully someone here has an answer.
I'd like to build a webpage that is able to interpret an .rtf document on the server and then echo the text in the browser re-using only the bold, italic, underlined tags and bulleted and numbered list tags. Preferably using PHP, but if it's something else, that would be fine (I'd just have learn that language then a bit too, I guess).
Many thanks in advance!
Cheers!

A: Check out Markdown. It's a text to HTML format very similar to what you find here on StackOverflow.
There are several PHP ports. I suggest PHP Markdown.

A: There's an RTF to HTML class on PHPClasses... no idea how goo dit is though.


text:
Q: A Twist on the Birthday Problem I was asked the following question: given a debate team with 27 members, what is the probability that at least three members have a birthday on the same month?
   Since this is an at least question, it is easier to find the complement.
$P(x\geq3) = 1 - (P(0) + P(1)+P(2))$
$P(0) = (\frac{11}{12})^{27} $
   $P(1) = 0$
   $P(2) = 1 \cdot(\frac{1}{12})\cdot(\frac{11}{12})^{25} $
Therefore, $P(x\geq3) = 0.895.$
But is this the right approach?

A: This is actually a pigeonhole principle question not a probability question.
Imagine that no month has three or more birthdays in it. There are 12 months so there could only be 24 debaters. As you have 27 debaters then at least one month must have at least 3 people in it. So the probability is 1.


text:
Q: Render Self-Closing Tag in ASP.NET custom control derived from Control I'm working on a Facebook FBML controls library and would like to create my FBML controls somewhat patterned like the ASP.NET WebControls library.  I have a base class that handles rendering by default; here's my render method:

        protected override void Render(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);

            if (UseXfbmlSemantics)
            {
                writer.RenderBeginTag(ElementName);
                writer.EndRender();
                writer.RenderEndTag();
            }
            else
            {
                writer.RenderBeginTag(ElementName);
                writer.RenderEndTag();
            }
        }

What I would like is for the rendering to be modified based on UseXfbmlSemantics - if it's true, it should render, for instance:
<fb:name uid="10300399458"></fb:name>
When it's false, it should render with a self-closing tag:
<fb:name uid="10300399458" />
I can get the "true" condition to work almost correctly, but the self-closing tag seems to be incompatible with the Render- set of methods.  Unfortunately if that's the case it also means that the AddAttributesToRender pattern wouldn't work, either.  What it's actually producing is this:

        <fb:name uid="10300399458">

        </fb:name>

How can I get HtmlTextWriter (or which HtmlTextWriter do I need to use) to make it render a self-closing tag?  Or, at the very least, how can I make it not render that interim space (so that the opening and closing tags are immediately next to one another)?

A: Since this is the top SO question that comes up when searching for "HtmlTextWriter self closing tag", this is for anyone coming here that wants to know how to do it:
writer.WriteBeginTag("tag");
writer.WriteAttribute("attribute", "attribute value");
// ... add other attributes here ...
writer.Write(HtmlTextWriter.SelfClosingTagEnd);

A: This should get you going - it will render as <fb:name uid="00101010101"/>. You could also override the RenderBeginTag, RenderContents, RenderEndTag. Depending on what you are doing there may be some other things going on in RenderControl that you need. You could also look into using a ControlAdapter, this may give you better separation of control functionality VS control html writing.
public  class FbName:System.Web.UI.WebControls.WebControl
{

    protected override string TagName
    {
        get
        {
            return "fb:name";
        }
    }

    public override void RenderControl(HtmlTextWriter writer)
    {
        RenderBeginTag(writer);// render only the begin tag.
        //base.RenderContents(writer);
        //base.RenderEndTag(writer);
    }

    public override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.Write("<" + this.TagName);
        writer.WriteAttribute("uid", "00101010101");
        writer.Write("/>");

    }
}

-Jason

A: I'd recommend to use HtmlTextWriter constants:
    protected override void Render(HtmlTextWriter writer)
    {
        AddAttributesToRender(writer);
        writer.Write(HtmlTextWriter.TagLeftChar); // '<'
        writer.Write(this.TagName);
        writer.Write(HtmlTextWriter.SpaceChar); // ' '
        writer.WriteAttribute("uid", "00101010101");
        writer.Write(HtmlTextWriter.SpaceChar); // ' '
        writer.Write(HtmlTextWriter.SelfClosingTagEnd); // "/>"
    }

A: if you use Visual studio go by these steps:

Tools ---> Options ---> Text Editor ---> HTML ----> Formatting --->
  remove Auto insert close tag


text:
Q: One fileserver and two replicated nodes with samba daemon I have to set up a  new infrastructure for a project. We have two offices with a slow up- and downlink (2 MBit SDSL) to the internet and one server C with a 100 MBit link to the internet. Then there is a Ubuntu machine in each office (A and B) with a samba share so that each user in the particular office can mount that share under a drive letter on Windows. This way they have a fast access because the internal LAN uses 100/1000 MBit.
Next the two Ubuntu machines (A and B) and the Ubuntu Server (C) should replicate the data between them. They all have a 1 TB drive and the data on them should always be exactly the same.
For that reason I tried GlusterFS on Server A and C but is seems not to be very reliable (server B does not exists for now). For a quick test I copied a 10 MB file to the glusterfs mountpoint on Server A. In the same second the file appeared on server C but was only 6 MB. It takes up to 30 minutes until the file on server C got its correct size of 10 MB. Because of that I do not really want to use it in a productive environment.
The main problem is that the users in the office want to have a fast connection to the local server and if someone changes, deletes, moves or creates a file it should also be changed, deleted, moved or created on the other servers. Maybe it would be enough to only use the servers A and B as a cache but what is the best service for this?
I really appreciate your help. It would be nice to find a suitable solution. Thank you!

A: The standard solution to this problem is to utilize a program called Unison. Their Web page states:

Unison is a file-synchronization tool for OSX, Unix, and Windows. It allows two replicas of a collection of files and directories to be stored on different hosts (or different disks on the same host), modified separately, and then brought up to date by propagating the changes in each replica to the other.

The integration with a Samba Share is easy enough: it is discussed in detail on the Samba Wiki pages.
Basically, it consists of four steps:

*

*User synchronization. It is most convenient to have the same set of users of both systems. This is especially easy if the shares belong to the same user, and anyone can modify their content. But you can also setup your system to have all of the users of both LANs, it just depends on you.

*Passwordless access. This is necessary to allow automatic, yet secure ssh connections between the two systems.

*Unison setup (easiest part, just a one-liner).

*crontab setup. This is necessary to synchronize your two machines every minute (cannot be done more often via crontab). This is a one-liner too.
This is basically all.


text:
Q: Video Shortcode Only Returning a Link I am trying to dynamically load a video in the media library using the built in MediaElement player. To do this, I am using the do_shortcode() function to run the [video] shortcode and build up the necessary divs and such.
However, no matter what I do, the do_shortcode() with [video] only returns a href link and not the video player. Any suggestions?
<?php echo do_shortcode("[video src= 'link_to_my_video.mp4 ']"); ?>

A: Wordpress has this little minimally documented function, wp_video_shortcode()
Just pass an array with the necessary information as if you were writing out the shortcode.


text:
Q: Python - matplotlib: Trying to animate decision boundary plot without points being animated def sequential_deltaRule(X, W, T, maxEpoch):
    learningRate = 0.001
    currentEpoch = 1
    while currentEpoch <= maxEpoch:
        for index, xCol in enumerate(X.T):
            Wdelta = -learningRate * np.dot(np.dot(W[0], xCol) - T[index], xCol.T)
            W = W + Wdelta
        currentEpoch += 1
    return W

def plotclass(lhs, rhs):
    x, y = lhs[0], lhs[1]
    k, l = rhs[0], rhs[1]
    plt.scatter(x, y, color='black')
    plt.scatter(k, l, color='red')
    plt.show()
    return None

def plotBoundary(weights):
    x = np.linspace(-1.5, 3, 100)
    y = -(weights[1] * x + weights[0]) / weights[2]
    #fig = plt.figure()
    ax = plt.axes()
    ax.plot(x, y, color='blue')

def generateData(datapoints):
    n = datapoints
    mA, sigmaA = np.array([2.0, 1]), np.array([0.3, 0.3])
    mB, sigmaB = np.array([-0.1, 0.0]), np.array([0.3, 0.3])
    classA = (np.random.normal(size=(2, n)).T * sigmaA + mA).T
    classB = (np.random.normal(size=(2, n)).T * sigmaB + mB).T
    return classA, classB

W1 = sequential_deltaRule(data, weights, targets, 20)[0]
plotBoundary(W1)
plotclass(classA, classB)

I'm trying to plot the points from the two classes and then animate the decision boundary. But at this moment I only get one image.
What I'm trying to do is like this video https://www.youtube.com/watch?v=7RgoHTMbp4A&t=306s&ab_channel=NeuralNine but I dont want the points to animate, only the deicison boundary.


text:
Q: Overwrite foundation buttons The documentation (http://foundation.zurb.com/docs/components/buttons.html) doesn't say anyting about changing the background of a button. How can I do this in sass (custom.scss)?
I can't create a new buttonclass because I need to change the styling of generated components in Drupal.

A: If you can not create a new class, can't you just extend the existing class?
You can just do this:
button,
.button,
a.button,
input.button
{
  background-color: green;
}

A: Since I cannot add comment so I will just write it as an answer. Do you want to change background color of all buttons? There is a file for you to customize these settings, by default these are commented. You will find some lines for background color settings like this:
In Foundation 5, its in _setting.scss
// $primary-color: #008CBA;
// $secondary-color: #e7e7e7;
// $alert-color: #f04124;
// $success-color: #43AC6A;
// $warning-color: #f08a24;
// $info-color: #a0d3e8;

Uncomment the line you want to customize settings and change the value of color as you want. In the file that you define styles for buttons, @import the file that has customized settings (_settings.scss in this case). This will also change color of other elements importing the customized setting file.
Another way, go to definition for @mixin button and change value of $bgas you want.
&.secondary { @include button-style($bg:$secondary-color); }
  &.success   { @include button-style($bg:$success-color); }
  &.alert     { @include button-style($bg:$alert-color); }

&.disabled, &[disabled] { @include button-style($bg:$primary-color, $disabled:true);
    &.secondary { @include button-style($bg:$secondary-color, $disabled:true); }
    &.success { @include button-style($bg:$success-color, $disabled:true); }
    &.alert { @include button-style($bg:$alert-color, $disabled:true); }

A: Try these properties in your SCSS file.
$button-background  - Background color of the button.

$button-background-hover - Background color of the button on hover.

$button-color - Text color of the button.

Source: Foundation CSS - Buttons


text:
Q: Python multiprocessing worker queue for Tensorflow Tensorflow can run for a long training session and that can crash a server between refreshes of a page.
I'm hoping I can use the following from a previous answer to fix this:
I have a python function that has to run 12 times in total. I have this set up currently to use Pool from the multiprocessing library to run up to all of them in parallel. Typically I run 6 at a time because the function is CPU intensive and running 12 in parallel often causes the program to crash. When we do 6 at a time, the second set of 6 will not begin until all of the first 6 processes are finished. Ideally, we would like another one (e.g. the 7th) to kick off as soon as one from the initial batch of 6 is finished- So that 6 are running at once while there are more to start. Right now the code looks like this (it would be called twice, passing the first 6 elements in one list and then the second 6 in another:
from multiprocessing import Pool

def start_pool(project_list):

    pool = Pool(processes=6)
    pool.map(run_assignments_parallel,project_list)

So i have been trying to implement a worker/queue solution and have run into some issues. I have a worker function that looks like this:
def worker(work_queue, done_queue):
    try:
        for proj in iter(work_queue.get, 'STOP'):
            print proj
            run_assignments_parallel(proj)
            done_queue.put('finished ' + proj )
    except Exception, e:
        done_queue.put("%s failed on %s with: %s" % (current_process().name, proj,        e.message))
    return True

And the code to call the worker function is as follows:
workers = 6
work_queue = Queue()
done_queue = Queue()
processes = []
for project in project_list:
    print project
    work_queue.put(project)
for w in xrange(workers):
    p = Process(target=worker, args=(work_queue, done_queue))
    p.start()
    processes.append(p)
    work_queue.put('STOP')
for p in processes:
     p.join()
     done_queue.put('STOP')
for status in iter(done_queue.get, 'STOP'):
    print status

project_list is just a list of paths for the 12 projects that need to be run in the function run_assignments_parallel.
The way this is written now, the function is getting called more than once for the same process (project) and I cant really tell what is going on. This code is based on an example i found and I am pretty sure the looping structure is messed up. Any help would be great and I aplogize for my ignorance on the matter. Thanks!

This seems to run paths, like filenames with python inside, I'm hoping to place this in my views path of my django server and get it to run through the tensorflow training sessions

A: Here is a minimal running example made from your snippets. I converted your code to Python 3 as Python 2 is deprecated and no new code should be written with this version.
from multiprocessing import Process
from multiprocessing.process import current_process
from queue import Queue

def worker(work_queue, done_queue):
    proj=None
    try:
        for proj in iter(work_queue.get, 'STOP'):
            print(current_process().name, "#", proj)
            done_queue.put('finished ' + proj )
    except Exception as e:
        done_queue.put("%s failed on %s with: %s" % (current_process().name, proj, e.args))
    print(current_process().name, "#", "Quit")
    return True

def main():
    workers = 6
    work_queue = Queue()
    done_queue = Queue()
    processes = []
    project_list = list("ab")
    for project in project_list:
        work_queue.put(project)
    for w in range(workers):
        p = Process(target=worker, args=(work_queue, done_queue))
        p.start()
        processes.append(p)
        work_queue.put('STOP')
    for p in processes:
        p.join()
        done_queue.put('STOP')
    for status in iter(done_queue.get, 'STOP'):
        print(status)

if __name__ == '__main__':
    main()

Process-1 # a
Process-1 # b
Process-2 # a
Process-2 # b
Process-2 # Quit
Process-3 # a
Process-3 # b
Process-3 # Quit
Process-4 # a
Process-4 # b
Process-4 # Quit
Process-5 # a
Process-5 # b
Process-5 # Quit
Process-6 # a
Process-6 # b
Process-6 # Quit

As you can see, each project is handled in each worker.
However the main processe hangs while joining processes because the Process-1 never terminates...
I think this is due to the iter(work_queue.get, 'STOP') call, and I don't understand what you try to achieve there.
The way you use queues seems strange to me.
I advise you to read deeper the queue module documentation, and in particular the task_done method, that must go in pair with get.
Finally, why did you not stick to the Pool solution that, I think, is the best suited to your problem.
Pool will automatically handle waiting queue and will make sure that as much as possible (6) workers are running concurrently.


text:
Q: Shell script for list of users by groups I want to write a shell script that generates a list of users. for each user display the username and ID and all groups the user is a member of
it means like GROUPS command but for all users and with their id
I used cat -d: -f1,3 /etc/passwd to show the users with their id but I don't know how can I use the groups for each line
would you please help me to write this script
thanks

A: Use this script:
#! /bin/bash
#
for i in $(cat /etc/passwd  | cut -d: -f1); do
   echo -n $i ": "
   grep $i /etc/group | cut -d: -f1 | tr "\n" " "
   echo
done

It will list all users in the system (included system) and print the list of groups near them. With a trivial modification you can print the numeric id too.


text:
Q: Bernstein-Chernoff inequality I am studying the proof of the following result due to Bernstein and Chernoff:
Let $\xi_1,\ldots,\xi_m$ be independent random variables with $|\xi_i|\leq 1$ for $i=1,\ldots,m$. Let $\beta = \sum_{i=1}^m\mathbb{E}[(\xi_i-\mathbb{E}[\xi_i])^2]$. Then
$$\mathbb{P}\bigg(\bigg|\sum_{i=1}^m \big(\xi_i-\mathbb{E}[\xi_i]\big)\bigg|\geq \gamma\bigg)\leq 2\exp\left(-\frac{\gamma}{4}\right),\text{ if }\gamma \geq \beta,$$ and $$\mathbb{P}\bigg(\bigg|\sum_{i=1}^m \big(\xi_i-\mathbb{E}[\xi_i]\big)\bigg|\geq \gamma\bigg)\leq 2\exp\left(-\frac{\gamma^2}{4\beta}\right),\text{ if }\gamma \leq \beta.$$
At some point, we have to obtain an upper bound of $\mathbb{E}[e^{y\xi_i}]$, with $0<y\leq 1$. To obtain this, the author uses exponential's series expansion, and then claims that the following inequality holds: $$\mathbb{E}[e^{y\xi_i}]\leq 1+\frac{y^2\mathbb{E}[\xi_i^2]}{2}+\frac{y^3\mathbb{E}[\xi_i^2]}{6-2y}.$$ I understand that, without loss of generality can assume that the random variables satisfy $\mathbb{E}[\xi_i]=0$, but this only justifies that the term with the first-moment disappears. Any ideas or possible proofs?

A: \begin{align}
\mathbb{E}\left[e^{y\xi_i}\right] &= \mathbb E\left[\sum_{n \ge 0} \frac{y^n\xi_i^n}{n!}\right]\\
&= 1 + \mathbb E\left[y\xi_i\right] + \frac12\mathbb E\left[y^2\xi_i^2\right] + \mathbb E\left[\sum_{n \ge 3} \frac{y^n \xi_i^n}{n!}\right]\\
&\underset{}{\le} 1 + \mathbb E\left[y\xi_i\right] + \frac12\mathbb E\left[y^2\xi_i^2\right] + \mathbb E\left[\sum_{n \ge 3} \frac{y^n \left|\xi_i\right|^n}{n!}\right]\\
&\underset{|\xi_i| \le 1}{\le} 1 + \mathbb E\left[y\xi_i\right] + \frac12\mathbb E\left[y^2\xi_i^2\right] + \mathbb E\left[\sum_{n \ge 3} \frac{y^n \left|\xi_i\right|^2}{n!}\right]\\
&\underset{}{=} 1 + y\mathbb E\left[\xi_i\right] + \frac12y^2\mathbb E\left[\xi_i^2\right] + y^3\mathbb E\left[\xi_i^2\right]\sum_{n \ge 0} \frac{y^n}{(n+3)!}\\
\end{align}
By simple induction $(n+3)! \ge 6\cdot 3^n$ then
\begin{align}
\mathbb{E}\left[e^{y\xi_i}\right] &\le 1 + y\mathbb E\left[\xi_i\right] + \frac12y^2\mathbb E\left[\xi_i^2\right] + \frac{1}6y^3\mathbb E\left[\xi_i^2\right]\sum_{n \ge 0} \frac{y^n}{3^n}\\
&= 1 + y\mathbb E\left[\xi_i\right] + \frac12y^2\mathbb E\left[\xi_i^2\right] + \frac{1}6y^3\mathbb E\left[\xi_i^2\right]\frac{1}{1-\frac{y}{3}}
\end{align}


text:
Q: How do I include the contents of a contenteditable element in a HTMX request? I'd like to post the contents of a contenteditable field/div whenever it changes. hx-trigger="change" didn't trigger, but using hx-trigger="blur" is okay. How do I submit the value of the contenteditable div in the request?

               Hello, I am a content editable field

A: I don't believe htmx supports submitting contenteditable values out of the box. You'd probably need to mirror the content text within contenteditable to a a hidden input and move the hx attributes to the parent div.
You could use something like https://alpinejs.dev/ or htmx's companion https://hyperscript.org/
With hyperscript you could do it with something like this:

    Hello, I am a content editable field

    <input type="hidden" name="editor" _="on keyup from #editordiv put its innerHTML into me" />

I found an old reference from the htmx Discord that offers another way of doing this:
<form hx-post="/whatever"
        hx-vals="javascript: editable:htmx.find('#myEditable').innerHTML"> ...


text:
Q: Test whether Reboot Required for (Windows Only) using Chef Inspec I am new to Chef Inspec, I want to test Reboot Required for (Windows Only) using Inspec code. Below is my code:
# Reboot Required Yes for windows

control 'PowerShellTest' do
  impact 0.1
    title 'Check powershell code inside inspec'
    desc  'TestCase for Powershell'
    if os.family == 'windows'
    describe command(shutdown /r) do
      its('action') { should be 'yes' }
      its('stderr') { should eq '' }
     its('exit_status') { should eq 0 }
  end
end


text:
Q: Use PHP's preg_replace() to return only the value inside the ? How would I use PHP's preg_replace() to return only the value inside the
 in the following string (it's HTML text loaded in a variable called $html):

I'm Header

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis.

Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

I've tried this: preg_replace('#
([.*])
.*#', '$1', $html), but to no avail. Am I regex-ing this correctly? And is there a better PHP function that I should be using instead of preg_replace?

A: ([.*]) means dot OR astersk
What you need is (.*?), which means any amount of any characters ungreedy
or
([^<]*) - which means any amount of any characters but not <

A: Here is how you do it using preg_replace:
$header = preg_replace('/
(.*)<\/h1>.*/iU', '$1', $html);

You can also use preg_match:
$matches = array();
preg_match('/
(.*)
.*/iU', $html, $matches);
print_r($matches);


text:
Q: Supervisord Hangs/Hungs on the Background after 10 minutes Somehow supervisord hangs/hungs 10 minutes after we do service supervisor start. Scripts initiated by supervisod still appears on the background as running but not functioning anymore. Any idea what could be the issue? Our current workaround was to install a cron job to restart supervisord every 10 minutes. supervisord version is 3.1.4 and python is 2.7.5

A: you can run your scripts command in the shell, don't start it in supervisord . and wait 10 minutes to see if it work well. you can also write some log in your script.I use supervisord in many projects and almost problem is command error or code error.


text:
Q: Stack Navigator error: undefined is not an object(evaluating 'this.props.navigation.state.params.username') Ever since I started using Stack Navigator with Drawer Navigator, this problem occurred. Right now, I think I am passing the parent in the navigate so that it will navigate to the correct screen.
  otherUser (username) {
 this.props.navigation.navigate('AppStackNav', { username: username });

}
This is how my navigation are setup. I am using Drawer, Stack, and Tab:
const TabNav = TabNavigator({
  Random: { screen: HomeScreen },
  Recent: { screen: RecentScreen },
  Trending: { screen: TrendingScreen },
  AllTime: { screen: AllTimeScreen },
}, {
  tabBarComponent: NavigationComponent,
  tabBarPosition: 'bottom',
  lazy: false,
  animationEnabled: true,
  swipeEnabled: true,
  tabBarOptions: {
    bottomNavigationOptions: {
      labelColor: '#333',
      rippleColor: 'white',
      tabs: {
        Recent: {
          barBackgroundColor: '#EEEEEE',
          activeLabelColor: '#212121',
        },
        Trending: {
          barBackgroundColor: '#00796B',
        },
        RegisterScreen: {
          barBackgroundColor: '#EEEEEE', // like in the standalone version, this will override the already specified `labelColor` for this tab
          activeLabelColor: '#212121',
          activeIcon: <Icon size={24} color="#212121" name="newsstand" />
        },
        AllTime: {
          barBackgroundColor: '#00796B'
        },
      }
    }
  }
});

const AppStackNav = StackNavigator ({
  OtherUserScreen: {screen: OtherUserScreen},
});

const AppDrawerNavigator = DrawerNavigator({
  TabNav: {screen: TabNav},
  LoginScreen: {screen: LoginScreen},
  RegisterScreen: {screen: RegisterScreen},
  ProfileScreen: {screen: ProfileScreen},
  UserListScreen: {screen:UserListScreen},
  HomeScreen: {screen: HomeScreen},
  AppStackNav: {screen: AppStackNav},
  OtherTagsScreen: {screen: OtherTagsScreen},
  QuoteMachineScreen: {screen: QuoteMachineScreen},
},
{
    initialRouteName: "TabNav",
    contentOptions: {
      activeTintColor: "#e91e63"
    },
    contentComponent: props => <SideBar {...props} />
  },

);

Also, I am still learning in React Native so any tips will greatly be appreciated.


text:
Q: New to Java Entities: Entity class complaining of being cast to itself I'm fairly new to Java Entities, and I've got a bit of a strange problem casting from a Query.getSingleResult() call. Here's a code snippet:
  LoaPoliciesConfig policy = new LoaPoliciesConfig();
  EntityManager em = getEntityManager();
  try
  {
     Query q = em.createNamedQuery("LoaPoliciesConfig.findByName");
     q.setParameter("policyName", policyName);
     Object ret = q.getSingleResult();
     policy = (LoaPoliciesConfig) ret;
  }

After working fine for ages, this has suddenly started giving me this error:
CRAAC.WebService.DataAccess.LoaPoliciesConfig cannot be cast to
CRAAC.WebService.DataAccess.LoaPoliciesConfig

At first this went away when restarting the server, but the last time it happens it seems to be here to stay.
getSingleQuery() returns an Object, and all the documentation I've found on the web so far seem to indicate this is the preferred way of doing it. So, my question is essentially am I do anything wrong in this code, or is it just the server getting confused somewhere along the way?

A: I suspect that you have 2 LoaPoliciesConfig classes on your classpath, such that they are being loaded/accessed from two different classloaders.
In this situation, class X from one classloader is not equivalent to class X from a second classloader, and you'll get the confusion that you're seeing. Check your classpath, and the classes available in your environment, and where they're loaded from (via getClass() and getClassLoader())


text:
Q: There is no SDK with the name or path "iphoneos4.0" I download a sample of UICatalog and run it.When I compile it ,it shows the failed message:There is no SDK with the name or path "iphoneos4.0".I find the "Base SDK" of UICatalog's Targets is iphone Device 4.0(missing).How can I solve this question and run it.
Thank you!

A: Ok, I've solved it.

*

*In Groups & Files go to Targets and select your target.

*Press Ctrl+I (or open the info in some other way)

*Set the Base SDK of your target

(The Base SDK should also be set at the project)

A: Steve nailed it.  This is an Xcode bug.  I loaded the NavBar sample and Xcode didn't even offer the simulator as an option, and it complained about the missing SDK even though it was set correctly in the project and wasn't set at all on the target.
Do what Steve said:
"The only way I could resolve it (in fact, the only way I could get the option of running in the simulator at all) was to change from debug to release and back. The dropdown still shows Base SDK Missing but if you click it, the simulator options are there and it builds."

A: Select the root level of the project, in "Groups & Files". It's blue. Then hit command-I to get its Info.
Pick "Build" from the segmented controller at the top of the info window. In the first section of that panel you'll see Base SDK as one of the first few lines of options. Select the latest version of the SDK you find in there, and close the window to save your options.
Build-and-run the project, and you should be good to go.
EDIT, because I see from the comments that people are finding this answer who have a slightly different question than the OP's, so here's one other thing to try. It could also be you have "iOS Device" selected as your build target. If so, and if what you really want is for it to launch into the simulator, select "Simulator" instead.

A: After loading the project into XCode..
Under Groups and Files

*

*right click on UICatalog<-(or your demo project name) and select Get Info

*in Base SDK select IOS Simulator 4.1

*Close and save info pane

*expand Targets exposing UICatalog<-(or demo project name)

*right click on UICatalog and select Get Info

*in Base SDK select IOS Simulator 4.1
Combo box in UICatalog project pane (upper left corner) should switch to "Device - 4.1 | Debug" instead of "No Base SDK"
if you Build and Run at this point you might get another error. If so, open the UICatalog combo and switch from Device to Simulator
The "official link" mentioned above states…
"Note: Targets can override build settings defined at the Project level. "
..but should probably read "will" instead of "can"

A: My problem was that in the sample code another xcodeproj was embedded. So I looked after that file with Finder, opened it with Xcode and than the same as Dan said: Project -> Edit Project Settings -> Under "Architectures" set Base SDK to "iPhone Simulator x.x" (the latest one you have installed)

A: I had the same issue with another Apple sample app.  The only way I could resolve it (in fact, the only way I could get the option of running in the simulator at all) was to change from debug to release and back.  The dropdown still shows Base SDK Missing but if you click it, the simulator options are there and it builds.
I think that's a bug.

A: Many answers here, none seem to be complete enough about this, and it's all a mess. But they are all helpful. Here, I just want to compile all helpful pieces in one answer. Thanks to Larry (who have almost everything compiled into steps already), Steve, Dan Ray, dkk, geowar and lqf.

This picture from apple is a little decieving and outdated (talking about iOS SDK 4.0 and we're currently at 4.1) but it does show where you should change the project settings. Just select iPhone Simulator 4.0 if it was previously on iPhone Device 4.0.
Other than that, they say "Targets can override build settings defined at the Project level". So, yeah, also go ahead, open Targets and set all of their Base SDK back to default by pressing delete on it. If they were bolded, they'll become regular indicating a default value, which should be iPhone Simulator 4.0 if you did the first step right.
Just realize there are many places where Base SDK can be wrong:

*

*Under Project Info

*Under Target Info

*Under different configurations for both Project and Target

And that under Target it should be set to default, which is value from Project.
There's still something about the overview combo sometimes having and sometimes not having more than 1 option such as "Device" and "Simulator" that I just couldn't understand yet, but this is another potential configuration place for Base SDK being wrong.

A: You have to make sure that you change to the "iPhone Simulator" under the project settings in the appropriate configuration (i.e. if you are building a debug build you have to change to the simulator under the debug configuration).
For some reason I was getting this error when I did change the simulator but realized that I was doing a debug build but changed to the simulator under the release configuration and not the debug configuration.

A: dkk's answer is what made things work for me.  I had to change the Base SDK on the target and not just the project.  Perhaps you have to do both.

A: I got a similar error after upgrading my iPhone to iOS4.2.1(8C148a). The situation is as following.
I was using Xcode 3.2.4, but it does not support iOS4.2.1. So I downloaded Xcode_3.2.5_and_ios-sdk_4.2_final.dmg which is 3.78GB requiring 9.53GB to install. Then I ran my ap with Xcode 3.2.5. That is where I got the above error message.
Now it is ok. I solve this based on Geowar's answer:

*

*For the official answer:
http://developer.apple.com/library/ios/#qa/qa2010/qa1701.html
Please be noted that if you have done as Geowar said and the message is still there. Try to close Xcode 3.2.5 and restart it. That is how it works for me.
Another thing is that if you have just upgraded to iOS4.2.1 like me. When you try to load the a/p from Xcode 3.2.5 the first time. Xcode 3.2.5 may still give you "No provision iOS device connected". Please try to go to organizer and click on your iPhone under DEVICES on the left bar. Wait for a while to let Xcode in sync with your iPhone with iOS4.2.1. Then it will work. At least it work for me.
Jesse

A: Ok, so I struggled through this too. Based on some of the answers above and from the apple development forum, I was able to figure out what worked for me.
In XCODE, if you notice that the pull down at the top left of the window says "BASE SDK MISSING", you are going to get this error "There is no SDK with the name or path "iphoneos4.0"". To fix the problem:

*

*double click on Group & Files in the upper part of the left pane of xcode. This will open a window

*go to the Build tab of the new window

*click on the row that says "BaseSDK" and select "Latest iOS (currently set to iOS 3.2)

*The Configurations pull down near the top should now say "All Configurations". If not, set it.

*close the window.

*Now if you try to build, you will get a different error, something like: Code Sign error: The identity 'iPhone Developer: x Xxxxx' doesn't match any identity in any profile ...

*So, now what you need to do in xcode is to click on the pull down in the upper left corner (the pull down that had the original BASE SDK MISSING indication, but probably has something different now), and make sure that both "Simulator" and "Debug" are checked as options in the pull-down.

*now you should be good to go.

A: I just went Project -> Edit Project Settings -> Build -> then change the Base SDK to iPhone 4 simulator or I'm assuming whichever SDK you want to use.
I never had to specify the build for a given target, although my program was created on a mac that was already configured to use the iPhone 4.0 simulator.. so perhaps the targets were set for the simulator SDK and the project itself wasn't? Either way... just glad it works.

A: I was having the same problem and what I did to solve it was:

*

*Go to Menu Project

*Go to Set Active SdK

*Select the option SIMULATOR instead of DEVICE

*Build and Run and the ERROR has gonne!

I hope it works for you guys... =)

A: I just had a situation where I changed the Base SDK to 4.2 on my project after updating to Xcode 3.2.5, but I kept on getting the "There is no SDK..." error. I finally opened the project file (MyProject.xcodeproj/project.pbxproj) in a text editor and looked around. There was no mention of 4.0 anywhere, only 4.2. BUT when I then saved that file, it all started working in Xcode. Perhaps some permission on the file or something else. Have no idea really, but it worked.

A: I got this error when one of my configurations still referenced an old (iOS) SDK. Note that the error shouldn't have come up when I tried to build a totally different configuration (with correct Base SDK setting), so this smells like an XCode bug to me.
People suggesting that you don't set the base SDK in at target-level have probably never created projects which contain targets for different platforms all in one project file (in my case Mac and iOS targets, so setting the base SDK once in the project file is nonsense advice).


text:
Q: Trying to print an url that is inside of a Javascript Object I'm trying to do this in parse. So i want to get the url in the image:
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({

success: function(results) {
    // Do something with the returned Parse.Object values
    for (var i = 0; i < results.length; i++) {
    var object = results[i];
    if(object.get("ImageFile") !== '' && typeof object.get("ImageFile") !== 'undefined' || object.get("ImageFile") == true) {
        var file = object.get("ImageFile");
        console.log(file);
        var liga = file.url;
        document.getElementById(".imagen").innerHTML = liga;
    }

The console log throw me this, the url I need, so How can i print that url in order to show the image? (for example ):
b.File {_name: "tfss-b59f1559-1ac4-4b49-8191-f167a95b7e69-Ruben-Espinosa-1.jpg", _url: "http://files.parsetfss.com/9ab97f5c-e03d-4602-a7be…-1ac4-4b49-8191-f167a95b7e69-Ruben-Espinosa-1.jpg"}

Thanks

A: To acces the _url field use:
var liga = file["_url"];

A: This is the correct code
    // ENCHARCAMIENTOS
    var Encharcamientos1 = Parse.Object.extend("Report");
    var query = new Parse.Query(Inundaciones1);
    query.equalTo("Tipo_Reporte", "Encharcamientos");
    query.find({
  success: function(results) {
    // Do something with the returned Parse.Object values
    for (var i = 0; i < results.length; i++) {
    var object = results[i];
    if(object.get("ImageFile") !== '' && typeof object.get("ImageFile") !== 'undefined' || object.get("ImageFile") == true) {
        var file = object.get("ImageFile");
        var liga = file["_url"];
    }
     L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup('
 ' + object.get('Tipo_Reporte') + '

Fecha: ' + object.get('Fecha') + '

Hora: ' + object.get('Hora') + '

' + '

Comentarios:
 ' + noundefined(object.get('Comentario')) + '
').addTo(Encharcamientos).addTo(todos);
    }
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});

A: You have two options:
var liga = file["_url"];

Or
var liga = file._url;