text:
Q: ORM vs serialized array? I'm just learning about ORM's, and am wondering... if you have an object (a JSON let's say... and assume it's dense, contains nested objects, has a total number of properties that could vary from object to object, etc), what would be the argument against simply turning it into a serialized array, and storing it in a table?
The object I'm describing likely won't normalize anyway; it would have an indeterminate amount of properties meaning an indeterminate columns... map this kind of thing to a table would require an insane amount of rows and keys all over the place.
If you're ultimately planning on querying the db for an object to then process via code, what is the downside to simply serializing it or using some kind of OODB? What would I gain by using an ORM?

A: My experience is that because the Storage layer for the ORM expects the storage data to be dynamic and therefore holds no preconceptions about its format, it can be better equipped to deal with the exceptions to the norm. (Not actual error exceptions but cases where your object doesn't match your Database Schema)
When you're dealing with Dynamic objects, the rigidity enforced by classic storage generally forces you to either handle the exceptions to norm or create a database schema so loose, that using it defeats the optimisations generally granted by the Database engine; think computed stats and various indices.
However, ultimately I think you've hit the nail on the head in your second paragraph: If it won't normalise then you will have trouble representing it into a schema that's good enough for your database to work with efficiently.
Sure you could serialise the entire object to an array and store that, but you lose the potency of good indexing, full text search and being able to cross-reference objects without having to do multiple reads.
An example for the above, say your DB is modelling ecommerce orders and you want to find subsequent purchase orders to the initial one. The database would need to know how to read each serialised item to find it's parentId property and then rescan the table for matches.
Long story short, ORMs are an answer to a problem that's been extant since Object Orientated programming was dreamed about - Don't worry about it and use them, unless you're sure that your data structures/schema are rigid and sensible to SQL.


text:
Q: Calling a function from a string (key[:-1]()) Basically I have a list of key:items in a dictionary, and I am using a loop to find the key that matches the item I get, and I have functions for every key. The keys are numbered though, so I need to take off the last number.
This leaves me with needing to call a function from a string like the one in the subject:
key[-1]()

key[-1] actually is a string that returns something like scalcs, and that is the name of a function of mine that I then need to call.
I've searched around and have seen stuff about classes. I'm new and honestly have never worked with classes at all and have a lot of code and a lot of these functions. I would rather not do that method if at all possible.
d = {key1: item1, key2: item2, akey1: item3, akey2: item4, dkey1: item1, dkey2: item2}

I want to call key, akey, or dkey when my value matches that of the value attached to the key in the dictionary.
So I will loop through d like this:
        for key, value in d.items():
        if id == value:
            print key[:-1]

Now I just need to call that key[:-1]

A: def hello_world():
    print "hello world"

d = {'hello':hello_world}

d['hello']()

locals()['hello_world']()

A: Instead of storing the name of your function as key of your dictionary, you could try to store the function itself:
>>> f = lambda x:x+1
>>> g = lambda x:x-1
>>> D = {f:'0', g:'1'}
>>> (F,) = [k for k,v in D.items() if v=="0"]
>>> F(3)
4

If you need to keep your keys as strings, then create a second dictionary (key_as_string, corresponding_function) with all the correspondences and just retrieve the function corresponding to the key you got at the previous step.

Note that you need to be very careful that you don't have multiple keys with the same value, otherwise, there's no telling that you'll get a unique function. The safest way would be to build a reverse dictionary of what you have: (some_string_index, a_function).
Note also that the function is just an object: in the example above, I used something very simple like a lambda, but you could use something far more complicated:
def a_function(...):
    ...

your_dictionary = {a_function: your_index}
safer_dictionary = {your_index: a_function}

A: I'm not entirely sure that I understand your question. Is the following right?

You have dictionaries
d1 = {key1: item1, key2: item2, ...}

and
d2 = {key1: function1, key2: function2, ...}

Given an item item2, you want to find function2.

If that's it, then you should store the information you have differently, in the form
d = {item1: function1, item2: function2, ...}

The function you want is then d[item2].

To generate d from d1 and d2, you can do
d = {item: d2[key] for key, item in d1.items()}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Package.json - set main directory I'm building a library with no default export, but a whole set of sub-exports. It's documentation for a set of APIs, so each API is exported from its own sub-directory. There is no central API info that should be exported from, say, dist/index.js, but instead, there's dist/api-one/index.js, dist/api-two/index.js, etc.
Currently, I'm importing like so: import { SomeFeatureOfApiOne } from 'my-package/dist/api-one
But it'd be nice to be able to get rid of the dist in the import path, since everything will have it. I know the files parameter just determines which directories are included in the export, so that doesn't work, and it appears that main is for the actual module file, not a directory.
Is there a way to do this? I was thinking of maybe a postinstall script that moves the sub-directories from /dist to root, but that feels super hacky to me, so I was hoping there was a neater way.

A: Add:
"exports": {
    "./*": "./dist/*.js"
},

to your package.json
You can read more about "exports" here - https://nodejs.org/api/packages.html#subpath-exports


text:
Q: ¿Que sucede cuando abro un FileReader/FileWriter? tengo una duda la cúal trata básicamene sobre las clases FileWriter y FileReader. Cuando yo instancio estas clases entendí que se abre una conexión entre el archivo elegido y el programa java, ahora, porque tengo que cerrar esta conexión? ¿Qué sucede internamente?
¿Cómo trabaja el BufferedReader a diferencia de FileReader y FileWriter?

A: BufferedReader y FileReader son clases que extienden de la clase Reader y sirven para implementar el patrón de diseño decorador. Este patrón se caracteriza por agregar funcionalidad de manera dinámica en tiempo de ejecución. Lo que tienes con la clase java.io.Reader es un contrato que establece cómo leer caracteres de un flujo de datos (stream). La clase FileReader va a leer caracteres de un archivo (cualquiera que fuese su formato). La clase BufferedReader decora a un java.io.Reader para facilitar la lectura de los caracteres que existe en ese lector al preconsumir su contenido y almacenarlo en un buffer, de manera que agiliza la lectura de los caracteres en el flujo de datos.
Para leer los caracteres de un archivo, basta con hacer esto:
FileReader reader = new FileReader("/ruta/del/archivo.ext");

Pero el FileReader no tiene ningún método adicional a los de Reader, por lo cual la lectura directa de esta clase sería de caracter por caracter o de un conjunto de caracteres almacenado en un arreglo (denotado por el método FileReader#read(char[], int, int).
Para agilizar el rendimiento de la aplicación en estos casos, lo que se suele hacer es decorar la instancia de FileReader con una instancia de BufferedReader, de esta manera:
BufferedReader reader = new BufferedReader(new FileReader("/ruta/del/archivo.ext"));

Ahora, siempre que se trabaja con un archivo físico, se abre una conexión a dicho archivo y se dice que la aplicación está utilizando el archivo. Al no cerrar esta conexión vía Closeable#close el sistema operativo marcará que la aplicación continúa utilizando el archivo, generando así un problema. Siempre se deben cerrar los recursos.
Tal como menciona @juliansalas, desde Java 7 puedes ahorrarte la llamada al método close al utilizar try-with-resources. Acá un ejemplo:
try (BufferedReader reader = new BufferedReader(new FileReader("/ruta/del/archivo.ext"))) {
    //consume los datos del reader
    //...
} catch (IOException e) {
    //maneja tus excepciones, SIEMPRE
} /*
    no es necesario agregar un bloque finally para cerrar los recursos
    puesto que esta forma de utilizar try ya cerrará los recursos
    por ti y manejará el caso en que la variable `reader` no haya
    sido inicializada
*/

A: Para acceder a un archivo el sistema operativo tiene que proveer descriptores de archivos que son, en cierta medida, escasos.  Lo que ocurre cuando un program abre muchos archivos y no los cierra es que agota los descriptores que el sistema le provee a su proceso.
En programas pequeñitos que abren pocos archivos es posible no darse cuenta de esto, pero en programas más complicados o programas que corren por mucho tiempo (e.g., servidores), lo que ocurre en algún momento es que se agotan y el programa se queda sin poder abrir archivos nuevos.

¿Cómo trabaja el BufferedReader a diferencia de FileReader y FileWriter?

El BufferedReader es un decorador que añade funcionalidad a un Reader de base.  El objetivo es que la manera más económica de leer de un archivo es en bloques, pero muchos programas prefieren leer un octeto o caracter a la vez.  El BufferedReader soluciona esto leyendo un bloque a la vez del Reader de base, guardándolos temporeramente, y sirviéndolos poco a poco a su consumidor.

A: Cuando tu creas una conexión entre el fichero y el programa generas un Stream, estos Stream actúan como un canal entre el programa y el fichero, en ese canal se envía la información en bytes requerida. Entonces si no cierras puede que sigas usando los recursos de tu máquina que se usaron para ese stream, asi al cerar close(), liberas los recursos usados para el paso de informacion entre el canal.
FileReader y FileWriter son clases que se suelen usar para leer y escribir archivos de texto al usar 16 bits para el flujo de caracteres BufferedReader puede mejorar el rendimiento utilizando el bufer para la lectura de esos caracteres.
Desde la versión 7 de java ya no se usa close() en su lugar puedes capturar la excepción automáticamente con:
try{} y cath(){}


text:
Q: tableau divide one measure by another I have data like below in Tableau.
school  student marks
a       xy      5
a       xy      10
a       ab      15
b       cd      20
b       cd      25
a       cd      30

I want to find total marks, count of marks and average marks by student and school
in case of the below two tables i was able to create first 3columns, how could i create the 4th column? 2nd and third columns are measures.
Is it possible to perform a row level calculation?
student sum of marks    count of marks  average marks
xy      15              2               7.5
ab      15              1               15
cd      75              3               25

school  sum of marks    count of marks  average marks
a       60              4               15
b       55              2               27.5

A: Yes, you can create a calculated field as "average marks":
SUM(marks)/COUNT(marks)

Or simply select average of that measure, instead Sum or Count (right click, Measure: Average)


text:
Q: What should I do when I get stuck with a task for so long? My team are using Scrum and we are new to this methodology. I use Essential Scrum as our guideline but I haven't finished it yet. On a chapter, it says the team should focus on idle tasks, not idle workers which I somewhat agree with it.
Anyway, it doesn't say (at least on that chapter) what to do or how to solve it. What are some good suggestion about how to tackle idle tasks?
Update
Idle task in this context means a task that has been in progress for a lot longer than we expect, for example, if a task is estimated to be finish in 2 hours but it has been taking 6 hours and not sure when it will be finished.

A: I use one of these options.
Which one to use has depended on the individual circumstances.

*

*break it down further

*move it back into the ready state if another task is currently the active one.

*if it is blocked by another task, enter that task and then enter it as a blocker

*accept the idling, increase work-in-progress limits and don't focus on cycle time.

Whatever you do, communicating to your team and to the appropriate level of management is required.

A: There are only two things you can do :

*

*adjust your plan, and see how to plan better in the future

*ask for help, although this can even prolong the delay


text:
Q: What is the main difference between Markov renewal process and Semi-Markov Process? In The literature, it was said that Semi Markov processes are a continuous-time extension of Markov Renewal Process.
We know that a sequence of bi-variate random variables {(Yn, Tn)} is called a Markov Renewal Process if {Tn} is a sequence of non-negative iid random variables and Markov Property must to be met. In Semi Markov Process, same thing was happened. What is the difference between SMP and RMP? What make an SMP an SMP?

A: After a lot searching, finally I found this link helpful.
the main difference between an MRP and a semi-Markov process is that the former is defined as a two-tuple of states and times, whereas the latter is the actual random process that evolves over time and any realisation of the process has a defined state for any given time. The entire process is not Markovian, i.e., memoryless, as happens in a CTMC. Instead the process is Markovian only at the specified jump instants. This is the rationale behind the name, Semi-Markov.

A: Markov-Renewal processes (MRP) encompass Semi-Markov Processes (SMP) as a special case. While SMP requires the memory of the process to be renewed each time it reaches a state, MRP relaxes this assumption. I.e., there can be states in an MRP where the Markovian assumption need not hold. Such states are classified as non-regenerative and their counterparts as regenerative. Consequently, a Markov Regenerative Process (MRRP), which is a part of MRP, is a more generalized version.
What are the applications of MRRP? Imagine a system performing a certain task at a particular rate. Two regenerative states are zero- and full-completion. But what if the system fails while attempting to complete? Well, the system's ability (to complete after it recovers from failure) is likely going to be impacted. So, the failure of the system is a non-regenerative state as the Markov assumption need not hold true.
Hope this helps!


text:
Q: Is it possible to pass a standard ado connection string to Invoke-SqlCmd Is it possible to use a connection string like:
Data Source=[server];Initial Catalog=[database];Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

or:
"Provider=SQLOLEDB.1;Persist Security Info=True;Initial Catalog=[database];Data Source=[server];uid=[username];pwd=[password];Pooling=true;Min Pool Size=10;Max Pool Size=500;Incr Pool Size=5;MultipleActiveResultSets=true;"

with Invoke-Sqlcmd?

A: Actually, Yes.
As of this writing the invoke-sqlcmd available in the SQLServer module includes a -connectionString parameter.

A: At the time this question was asked, no. More recently, yes, Invoke-Sqlcmd now supports a -ConnectionString parameter that accepts a standard database connection string as a value.
Previously, you'd need to break out each of the parameters in your connection string and match them up with the parameters that Invoke-Sqlcmd accepts.
If you had the flexibility and are stuck with a frozen legacy environment, you may wish to bodge Chad Miller's Invoke Sqlcmd2 and make it accept an ADO.NET connection string as one of its parameters:

https://gallery.technet.microsoft.com/scriptcenter/7985b7ef-ed89-4dfd-b02a-433cc4e30894


text:
Q: YUI Loader requests javascript files multiple times? I am using YUI 2.7.0 and the YUI Loader in several places in one page, and FireBug shows me that, for instance, yahoo-dom-event.js is being loaded several times (by pretty much all of the loader instances).
If my page has two "modules", and each one creates a YUI container, and uses the YUI loader to do so, then FireBug shows me that "container-min.js" is being requested twice.
Is this correct? Or am I doing something wrong?

A: Can you post some sample code? It should not be doing that. It should be detecting what you already have. You're not using the sandbox method, are you?
Also, you didn't ask this, but I'm curious why you are using the YUI loader in several places?  Why not load the bare minimum of what you need then lazy load the less using the onSuccess method? Or is that what you mean by several places (the onSuccess calls another)?


text:
Q: Unexpected End Of Stream error in reading xml data with InputStream of HttpsURLConnection public class MainActivity extends Activity
{
Button submit;
EditText textBox;

String xmlRequest = "<Request><Merchant_Number>111111111111</Merchant_Number><Terminal_ID>001</Terminal_ID><Action_Code>05</Action_Code><Trans_Type>N</Trans_Type><POS_Entry_Mode>S</POS_Entry_Mode><Track_Data2>71019520xxxxxx=</Track_Data2></Request>";

String domain = "www.somedomain.com/gateway.php";
String domainForSocket = "https://" + domain;
URL a;
String sucess = "sucess";
HttpsURLConnection urlConnection;
String header;
String writeData; // data which will be sent to server

byte[] outputInBytes;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    submit = (Button) findViewById(R.id.button1);
    textBox = (EditText) findViewById(R.id.editText1);

    writeData = xmlRequest;
    textBox.setText(writeData);

    // creating thread to run on background for network connection

    final Thread mThread = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

            try {
                a = new URL(domainForSocket);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {

                outputInBytes = xmlRequest.getBytes("UTF-8");

                urlConnection = (HttpsURLConnection) a.openConnection();
                urlConnection
                        .setFixedLengthStreamingMode(outputInBytes.length);
                urlConnection.setRequestMethod("POST");

                urlConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");

                urlConnection.setRequestProperty("Content-Length", ""
                        + outputInBytes.length);
                urlConnection.setRequestProperty("Accept-Encoding", "");

                urlConnection.setRequestProperty("Content-Language",
                        "en-US");

                urlConnection.setUseCaches(false);
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                // urlConnection.setDoInput(true);
                urlConnection.setInstanceFollowRedirects(false);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            // Log.v(sucess, "connectio open");

            try {

                OutputStream out = urlConnection.getOutputStream();

                out.write(outputInBytes, 0, outputInBytes.length);
                out.close();

                // Send request

                Log.v(sucess, "output sent");
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Output Error", "error in sending data to server");
            }

            try {

                InputStream a = urlConnection.getInputStream();
                InputStreamReader read = new InputStreamReader(a);

                BufferedReader br = new BufferedReader(read);

                String data = "";
                // Log.v("code execute", "i am here");
                StringBuilder total = new StringBuilder();
                StringBuffer ab = new StringBuffer();
                Log.v("result", "if you dont see then no data");

                while ((data = br.readLine()) != null) {
                    total.append(data);
                    Log.v("data", data.toString());
                }

                a.close(); // closing input string

            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Data Receiving Error",
                        "Error in receiving dat from server");
            }

            finally {
                // urlConnection.disconnect();
                try {

                    // mSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("Socket close Error", "cant close socket");
                }
            }

            // sending output

        }
    });

    submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            try {

                mThread.start();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    });

}

Above is my complete source code for XML HTTP Request. I getting XML response from the server. But I am getting the below error in logcat whenever I send request to the server. Can anyone help me on this issue.
Any help will be appreaciated.
Here is the log:
02-17 11:09:33.684: W/System.err(6446): java.net.ProtocolException: unexpected end of stream
02-17 11:09:33.689: W/System.err(6446):     at com.android.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:445)
02-17 11:09:33.690: W/System.err(6446):     at com.android.okio.RealBufferedSource$1.read(RealBufferedSource.java:168)

A: I found the solution.
I was not opening socket with android's inbuilt SSL socket library
javax.net.SocketFactory fact=SSLSocketFactory.getDefault();
         socket=fact.createSocket(addr, port);

This two line code wasted my four precious days :(


text:
Q: Cache-Control Header & Browser Caching IIS7 I am using Google Page Speed on my website in IIS7 and I was wondering how to set
Leverage browser caching - The following resources are missing a cache expiration
Leverage proxy caching - Consider adding a "Cache-Control: public" header to the following resources.
I am using doDynamicCompression in my web.config and little confused how to set these ? Hoping for some help
Note: Reference being used http://www.iis.net/ConfigReference/system.webServer/httpCompression

A: Under system.webServer in web.config set for example
<caching>
            <profiles>
                <add extension=".png" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" location="Any" />
                <add extension=".jpg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" location="Any" />
                <add extension=".gif" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" location="Any" />
            </profiles>
        </caching>

This can also be configured from IIS Manager under Output Caching but what the GUI doesn't do is set the 'location' attribute. Setting it to 'Any' will set Cache-Control:public.
You can read more about it here.

A: I imagine you already figured this out, but read up on setting content expiration in IIS here.
Note that this only applies to static content served by IIS. If you are looking to set caching headers for dynamic content (ASPX, PHP, ISAPI, whatever), you need to generate your own Expires and Cache-Control headers in your application. IIS will (quite correctly) not attempt to apply cache-control headers to dynamic pages that may include Set-Cookie headers or private data. ASP and ASP.net automatically set "Cache-Control: private" by default for all pages, but you can override that behavior on a per-response basis.


text:
Q: How to test AIR NativeWindow.invoke within the IDE? I am trying to debug an invoke handler. The Flash Builder IDE seems to stop the running AIR application when I start it the second time, so I never get to debug the second invoke (i.e. while the application is already running).
Any ideas?
(P.S. any clever way to tell the difference between the first and subsequent invoke events other than a global counter?)
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx"
                   invoke="onInvoke(event)">
    <fx:Script>
        <![CDATA[
            private function onInvoke(event : InvokeEvent) : void
            {
                logText.text +=
                    "invoke: event.arguments = " + event.arguments.toString() +
                    "; event.currentDirectory = " + ((event.currentDirectory != null) ? event.currentDirectory.nativePath : "null") +
                    "; event.reason = " + ((event.reason != null) ? event.reason : "null") + "\n";
            }
        ]]>
    </fx:Script>

    <s:TextArea id="logText" left="10" right="10" top="105" bottom="10"/>
</s:WindowedApplication>

A: The answer seems to be that one cannot test subsequent invocations inside the IDE.
That's okay: you can put a big, ugly testing button that calls whatever the invokeHandler() would have called when it detected that it was not the first occurrence.


text:
Q: What is the recommended approach to consume a ATOM feed from the CRM 2011 REST Service API This code receives a ATOM feed from the CRM 2011 REST Service API.  It works but it seem's very verbose but I can't find a more efficient way to consume the response.  I would appreciate any suggestions or if my question needs to be more specific I would ask is this the recommended approach?  I have found nothing on this in the CRM SDK or MSDN so far.
XmlDocument xml = new XmlDocument();
xml = xrm.GetXMLData(query);
XDocument xdoc = XDocument.Parse(xml.OuterXml);
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
XNamespace atom = "http://www.w3.org/2005/Atom";
foreach (var entity in xdoc.Descendants(atom + "entry"))
{
    var psi = entity.Element(atom + "content")
                     .Element(m + "properties")
                      .Element(d + "new_name");

    var status = entity.Element(atom + "content")
                        .Element(m + "properties")
                         .Element(d + "new_ExternalStatus");

    UpdateExternalDBStatus(psi.Value, status.Value);
}

A: From memory the API is OData based. Due to the design of OData (and the metadata it provides) you can actually use web-service style "Add Servicde reference" or the command line tools and Visual Studio will automatically construct the classes required for you to query the service. OData also provides an integrated query mechanism, so the classes also provide a LINQ style interface if required.
This blog post explains consuming OData in a little more detail: http://crdevelopment.net/2011/06/11/ebayodat/


text:
Q: jQuery: html() function get old data in form I am using jQuery to read data in a HTML page. On that page, I have a <form> element which contains some <input> tags for user to enter their values.
When being initialized, this form has some default values for those <input> elements. When I submit this form, I use the html() method to get the HTML string of current state of this page, but I do not why this result string is still contain old values (default input values), not the new ones.
Is there any way to update or persist the user-entered value to those <input> elements before calling html()? How can I get the string which contain newest value by using jQuery methods?
Thank you so much!

A: However, it is strange what you are trying to do, but all you need is to update the value attribute of the form elements. It can be done with the following code (put it in the form submit handler):
$("form input").attr("value", function() {
    return this.value;
});

DEMO: http://jsfiddle.net/BXha6/

A: By default the jQuery html() function will preserve the defaultValue and defaultChecked properties rather than using the current values/selections (just as JavaScript innerHTML does). To get around this you need to first use the jQuery prop(): Read the Documentation on prop().
For instance, given the code:
<form action='/'>
   <input type='radio' value='1' checked name='first' />
   <input type='radio' value='2' name='first' />

   <input type='checkbox' value='yes' />

   <input type='text' value='Start Text' name='second' />
</form>

then
   $('form').html()

Will always output that exact code, regardless of what values you've added/selected/modified.
To remedy that, just run a function to convert the element's values to properties:
$("form input[type='radio']").each(function(){
   if (this.checked){
      $(this).prop("defaultChecked",true);
   } else {
      $(this).prop("defaultChecked",false);
   }
});
$("form input[type='checkbox']").each(function(){
   if (this.checked){
      $(this).prop("defaultChecked",true);
   } else {
      $(this).prop("defaultChecked",false);
   }
});
$("form input[type='text']").each(function(){
   $(this).prop("defaultValue",$(this).val());
});

alert( $(form).html() ); //or var the_code = $(form).html();

You'll now have the HTML as your current page state is displaying it.

A: The textarea bit is a bit different if you were looking for how to do that element type:
 $("textarea").html( function() {
    return this.value;
});

http://jsfiddle.net/BXha6/7/


text:
Q: Update Site Name which is connected to Office 365 Group using CSOM I want to update Site Name using CSOM for SharePoint Site which is connected to Office 365 Group so at the end I want to update SharePoint Site Title and Office 365 Group Name both.
I have tried CSOM to update Site Title and Graph API to update Site Name as well Group Name
    var authManager = new PnP.Framework.AuthenticationManager(ClientId, CertificatePath, CertificatePassword, TenantId);
    using (ClientContext sourceSiteContext = authManager.GetContext("https://contoso.sharepoint.com/sites/SiteRenameTest"))
            {

                sourceSiteContext.Web.Title = "Updated Site Title";
                sourceSiteContext.Web.Update();
                sourceSiteContext.ExecuteQuery();

                sourceSiteContext.Load(sourceSiteContext.Site);
                sourceSiteContext.ExecuteQuery();

                var graphAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://graph.microsoft.com/.default" });
                var spAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://contoso.sharepoint.com/.default" });

                Microsoft.Graph.GraphServiceClient graphServiceClient = new Microsoft.Graph.GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider(
                async (requestMessage) =>
                {

                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", graphAccessToken);
                }));

                var group = new Microsoft.Graph.Group
                {
                    DisplayName = "Updated Site Title"
                };
                var response = await graphServiceClient.Groups[sourceSiteContext.Site.GroupId.ToString()].Request().UpdateAsync(group);
           }

Using above method, it updates Site Title and Office 365 Group Name but it does not update under Site Information Panel,

Now what is happening is if someone just open Site Information Panel(which still shows old Site Title) and cancel it without saving it, in background(after 10 minutes) Site Title and Office 365 Group changes with previous site name.
I have also tried to update Site Title using same way which SharePoint is using internally from UI i.e. _api/SP.Directory.DirectorySession/Group('{0}) (I need to find it using fiddler as there is no official documentation provided by Microsoft here), but it gives error like "The parameter __metadata does not exist in method Group.". I have tried with POST / PATCH call both and also tried to set ODataVersion but didn't work
HttpClient client = new HttpClient();
string requestDigest = await GetRequestDigest(spAccessToken, "https://contoso.sharepoint.com/sites/SiteRenameTest");
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("POST"), "https://contoso.sharepoint.com/sites/SiteRenameTest" + string.Format("/_api/SP.Directory.DirectorySession/Group('{0}')", sourceSiteContext.Site.GroupId.ToString()));
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"));
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spAccessToken);
message.Headers.Add("X-RequestDigest", requestDigest);
//message.Headers.Add("X-HTTP-Method", "PATCH");
//client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
//client.DefaultRequestHeaders.Add("OData-Version", "3.0");
//client.DefaultRequestHeaders.Add("prefer", "return=representation");

string requestContent = JsonConvert.SerializeObject(new ChangeSiteNameRequestModel()
{
    __metadata = new __Metadata() { type = "SP.Directory.Group" },
    displayName = "SiteRename-KV1"
});
message.Content = new StringContent(requestContent, Encoding.Default);
message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
HttpResponseMessage response = await client.SendAsync(message);

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    var responseContext = await response.Content.ReadAsStringAsync();
}
else
{
    var responseContext = await response.Content.ReadAsStringAsync();
}

Request Model schema which I am using
    public class ChangeSiteNameRequestModel
{
    public __Metadata __metadata { get; set; }
    public string displayName { get; set; }
}

public class __Metadata
{
    public string type { get; set; }
}

Below is the screen shot from Fiddler for API which SharePoint is using.

My end goal is here to update Site Name of the site which is connected to group in such a way that it will update site title (even in Site Information Panel), office 365 group name and also it should show updated site name in SharePoint Admin Center.
Any help would be highly appreciated here.

A: I found the solution with this link.
Here is my updated code which changes Site Name everywhere:
namespace ConsoleApp1
{
    internal class Program
    {

        static string CertificatePath = @"";
        static string CertificatePassword = "";
        static string TenantId = "";
        static string ClientId = "";
        static async Task Main(string[] args)
        {
            try
            {
                string siteUrl = "https://contoso.sharepoint.com/sites/SiteRename2";
                //await ShareDocumentDemo();
                var authManager = new PnP.Framework.AuthenticationManager(ClientId, CertificatePath, CertificatePassword, TenantId);
                using (ClientContext sourceSiteContext = authManager.GetContext(siteUrl))
                {
                    sourceSiteContext.Load(sourceSiteContext.Site);
                    sourceSiteContext.ExecuteQuery();

                    string newSiteTitle = "Update Site Title Final Test";

                    var graphAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://graph.microsoft.com/.default" });
                    var spAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://contoso.sharepoint.com/.default" });
                    await UpdateSiteName(siteUrl, spAccessToken, sourceSiteContext,newSiteTitle);
                    await SyncGroupProperty(siteUrl, spAccessToken, sourceSiteContext);

                }
            }
            catch (Exception ex)
            {

            }
        }
        public static async Task SyncGroupProperty(string siteUrl, string spAccessToken, ClientContext sourceSiteContext)
        {
            HttpClient client = new HttpClient();
            string requestDigest = await GetRequestDigest(spAccessToken, siteUrl);
            HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("POST"), siteUrl + string.Format("/_api/GroupService/SyncGroupProperties"));
            client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"));
            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spAccessToken);
            message.Headers.Add("X-RequestDigest", requestDigest);
            HttpResponseMessage response = await client.SendAsync(message);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
        }
        public static async Task UpdateSiteName(string siteUrl, string spAccessToken, ClientContext sourceSiteContext, string siteTitle)
        {
            HttpClient client = new HttpClient();
            string requestDigest = await GetRequestDigest(spAccessToken, siteUrl);
            HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("PATCH"), siteUrl + string.Format("/_api/SP.Directory.DirectorySession/Group('{0}')", sourceSiteContext.Site.GroupId.ToString()));
            client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"));
            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spAccessToken);
            message.Headers.Add("X-RequestDigest", requestDigest);

            string requestContent = JsonConvert.SerializeObject(new ChangeSiteNameRequestModel()
            {
                __metadata = new __Metadata() { type = "SP.Directory.Group" },
                displayName = siteTitle
            });
            message.Content = new StringContent(requestContent, Encoding.Default);
            message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            //message.Content.Headers.Add("Accept", "application/json;odata=verbose");
            HttpResponseMessage response = await client.SendAsync(message);

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
        }
        public static async Task<string> GetRequestDigest(string accessToken, string siteUrl)
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, siteUrl + "/_api/contextinfo");

            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            //message.Headers.Add("Content-Type", "application/json;odata=verbose");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
            HttpResponseMessage response = await client.SendAsync(message);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                RequestDigestResponse requestDigestResponse = JsonConvert.DeserializeObject<RequestDigestResponse>(responseContent);

                return requestDigestResponse.FormDigestValue;
            }

            return "";

        }

    }

    public class ChangeSiteNameRequestModel
    {
        public __Metadata __metadata { get; set; }
        public string displayName { get; set; }
    }

    public class __Metadata
    {
        public string type { get; set; }
    }

    public class RequestDigestResponse
    {

        public string FormDigestValue { get; set; }

    }
   }

Important: API Which I have used is not documented API by Microsoft.


text:
Q: How to make this CSS compatible with IE browsers? Well I have this css code this is for a site me and my friend are hosting.
But since it's up we have been getting a small complaints about IE users I have no idea on how I can make this with the IE browsers can any one help me with this? I've heard that it shouldn't be that hard but I have no idea where to start.
#table1 {

    font-family: open sans condensed;
    background-color: #FFF;
    border-collapse: collapse;
    margin: auto;
    padding: 100%;
}

#table11 {
    font-family: open sans condensed;
    background-color: #FFF;
    border-collapse: collapse;
    margin: auto;
}

th {
    font-family: open sans condensed;
    background-color: #CCC;
    font-size: 25px;

    border-style: solid;
    border-width: 3px;
    box-shadow: 0px 0px 8px #FFF;
    border-color: black;
    text-align: left;
    vertical-align: bottom;
}

td {
    background-color: #FFF;
    border-style: solid;
    border-width: 3px;
    box-shadow: 0px 0px 8px #FFF;
    border-color: black;
    text-align: left;
    vertical-align: bottom;
}

/*#table {
    top: -500px;
    /*Z-index: 19999px;
    background-color: #FFF;
    border-style: solid;
    border-width: 3px;
    box-shadow: 0px 0px 8px #FFF;
    border-color: black;
    text-align: left;
    vertical-align: bottom;
} This does nothing but it ruins the CSS if not commmented*/

a:link {
    font-size: 20px;
    vertical-align: middle;
    color: #A00000   ;
    font-family: julius sans one;
    font-weight: 900px;
    text-decoration: none;
    vertical-align: bottom;
}

a:visited {
    color: #000;
    vertical-align: middle;
    text-decoration: none;
    vertical-align: bottom;
}

a:hover {
    color: rgb(129,129,129);
    font-size: 20px;
    vertical-align: middle;
    text-decoration: underline;
    vertical-align: bottom;
}

a:active {
    color: #A00000   ;
    vertical-align: middle;
    text-decoration: none;
    vertical-align: bottom;
}

#buttonbox {
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    width: 205px;
    border-radius: 100px;
    border: 1px;
    border-style: solid;
    border-color: #CCCCCC;
    box-shadow: 0px 0px 9px 1px rgba(221,221,221,0.5);
    background-image: linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -o-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -moz-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -webkit-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -ms-linear-gradient(bottom, #04131A 24%, #282E2E 50%);

    background-image: -webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0.24, #04131A),
        color-stop(0.5, #282E2E)
);
}

#buttonbox:hover {
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    width: 205px;
    border-radius: 100px;
    border: 1px;
    border-style: solid;
    border-color: #CCC;
    box-shadow: 0px 0px 9px 1px rgba(221,221,221,0.5) inset;
    background-image: linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -o-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -moz-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -webkit-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -ms-linear-gradient(bottom, #04131A 24%, #282E2E 50%);

    background-image: -webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0.24, #04131A),
        color-stop(0.5, #282E2E)
);
}

#buttonbox:active {
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    width: 205px;
    border-radius: 100px;
    border: 1px;
    border-style: solid;
    border-color: #DDD;
    box-shadow: 0px 0px 9px 15px #CCC inset;
    background-image: linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -o-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -moz-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -webkit-linear-gradient(bottom, #04131A 24%, #282E2E 50%);
    background-image: -ms-linear-gradient(bottom, #04131A 24%, #282E2E 50%);

    background-image: -webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0.24, #04131A),
        color-stop(0.5, #282E2E)
);
}

#button {
    font-family: open sans condensed;
    color: #4d4d4d;
    font-size: 25px;
}

#button:hover {
    font-family: open sans condensed;
    color: #8d8d8d;
    font-size: 25px;
    text-decoration: none;
}

#div1 {

}

#body {
    background: rgb(33, 133, 197) url('images/escheresque_ste.png');
    margin: auto;
    top: 30px;
}

#submit {
    width: 155px;
    float: right;
}

#register {
    vertical-align: middle;
    margin: auto;
}

But currently I have no idea of if it is compatible with IE browser since it uses some of the new CSS3 styles. And also note I'm kinda new to CSS3/CSS but if you guys could help me out here I would be very grateful.
Here the HTML/PHP(Don't complain about the outdate PHP im working on it):
<?php
    //Connects to the Database
    include ('db.php');
    //Starts a query to fetch the data from the table
    $data = mysql_query("SELECT * FROM hf_osu") or die(mysql_error());
    if(!$data) {
        echo "3rr0rz";
        exit;
    }

?>

        <link rel="stylesheet" type="text/css" href="css.css">
        <link href='http://fonts.googleapis.com/css?family=Lobster|Fjalla+One|Julius+Sans+One|Passion+One:400,700,900|Lobster+Two:400,400italic,700,700italic|Open+Sans+Condensed:300,300italic,700&subset=latin,latin-ext,cyrillic-ext,cyrillic,vietnamese,greek,greek-ext' rel='stylesheet' type='text/css'>

                    Register here

                            Hackforums Name
                            Osu! name
                    <?php while($info = mysql_fetch_array($data)) : ?>

                            <a href="<?php echo $info['Hackforums_PLink'] ?>"><?php echo $info ['Hackforums_UName'] ?>
                            <a href="<?php echo $info['Osu_PLink'] ?>"><?php echo $info ['Osu_UName'] ?>

                    <?php endwhile; ?>

A: CSS3 support for Internet Explorer 6, 7, and 8

What is it?
IE-CSS3 is a script to provide Internet Explorer support for some new styles available in the upcoming CSS3 standard.

Read
selectivizr

A: CSS tricks, have a very good article on how to add IE only stylesheets, keep in mind, that you will have to make a completely new stylesheet for this. But i found it very useful.


text:
Q: Fusing linear acceleration and angular velocity to obtain linear acceleration relative to inertial reference frame First of all, I'm not a physics student (even though I've always been quite fascinated by it), and this can possibly be an easy problem, but here's my doubt.
I was reading this Wiki's article about Inertial Navigation Systems (ING), it says, at the end of the paragraph and I'm linking you to:

...
However, by tracking both the current angular velocity of the system and the current linear acceleration of the system measured relative to the moving system, it is possible to determine the linear acceleration of the system in the inertial reference frame.

What I think I understood...
I understood what's an inertial reference frame, it's basically a reference frame (to simplify, let's just talk about classical mechanics) where the inertia law of Newton is valid, that is an object traveling at a constant velocity will remain so unless an external force acts upon it.
I understood roughly what's the angular velocity and I understood that linear acceleration here is the proper acceleration measured by an accelerometer (that is an acceleration not due to gravity).
What I really did not understand
What I'm having difficulties with is:

*

*What does it mean that the linear acceleration was measured relative to the moving system? (Of course it may be more easy for you to read that paragraph than me to explain you)

*What would be the linear acceleration of the system in the inertial reference frame? I'm not asking you how to calculate it, but the conceptual meaning of it.

*Does this mean that the first linear acceleration measured by the accelerometer was not measured in an inertial reference frame? If yes, why? If yes, in which (type of) frame was it measured then?

*Why do we care about the linear acceleration in the inertial reference frame?

*Is the inertial frame of the system or of an another object?

A: By definition, a rotating frame of reference is not "inertial" - because objects in different locations that are stationary with respect to each other experience different "forces" (in particular, the Coriolis and centrifugal "force": these are fictitious forces that are needed to explain how objects appear to move as seen from a rotating frame of reference).
So if you have an accelerometer in a rotating object, that device will detect these fictitious forces. If you are trying to figure out how much your rotating frame of reference is moving "in the real world" you need to keep track of the rotation, and figure out what you would see if you could subtract these fictitious accelerations from the readings of the accelerometer.
Further - imagine you rotate your sensor by 90 degrees. Now your X is pointing in the Y direction, and the Y is pointing in the -X direction. So if you are recording an "X acceleration" you were actually moving in Y. Again, if you keep track of the motion / orientation of the rotating frame, you can correct for this.
I hope that clears up some of your confusion. I realize I didn't go point by point through your questions - but I think this should get you going.


text:
Q: Please give me an example of closed subspace of banach space under some conditions Please give me one example of Banach space $X$ and its closed subspaces $S,T,U$ which suffice following conditions.

Any of $S+T,T+U,U+S$ is not a closed subspace of $X$.

I can say there are some examples of Banach space $X$ and its closed subspaces $S,T$.
($S+T$ is not a closed subspace of $X$.)
one example:

$X=\{(y,z)|y \in C[0,1],z \in C[0,1]\}$, and its norm is $||(y,z)||=||y||_\infty+||z||_\infty.$
$S=\{(y,y')|y \in C^1[0,1]\},\ T=\{(0,z)|z \in C[0,1]\}.$

However, in case of three spaces, I have no idea. I would be really thankful if someone can help me.

A: Let $(V, ||\cdot ||)$ be a Banach space and $V_1 $, $V_2 $ two closed subspaces of $V$ such that $V_1 + V_2 $ is not closed. Consider a Banach space $X=V\times V\times V$ with norm $||(x,y, z) ||= \max\{||x|| ,||y||, ||z||\} $ and subspaces $S=V_1 \times V_1 \times V_2  ,$ $T=V_2\times V_1 \times V_2 ,$ $U=V_2 \times V_2 \times V_1 . $ Then the subspaces $S+T ,T+U , U+S $ are not closed.


text:
Q: redirect to page call from server in meteor I'm using iron router and
In the serve I've a http method
in server/methods.js
  '/fail':function(data){
            console.log("fail");
            console.log(data);
            return "
Your payment is failed.Click here to go back to site
"
        }

when calling this method I don't want to display simple message, I want to redirect to url
How to do this using iron:router
I tried using Router.go It is saying object has no method go
My router code is in
lib/router.js

EDIT
https://github.com/CollectionFS/Meteor-http-methods

The method above declared is a http-method using the above package
I'm using this method on  my server and
I've integrated some api in my application that api sends post request to /fail url
this is all working fine and I'm able to process the data also
but after processing the data I want to return to some url.

A: As far as I can see, the .go method only works on a Router instance, not on the Router global object itself, so maybe that is the issue?
Also, it appears that the .go function is only available on the client, not on the server. So that might be a thing as well...

A: You can always fall back to base HTTP.  This is the only method I've found that works.
'/fail':function(data){
        console.log("fail");
        console.log(data);
        this.response.statusCode = 302;
        this.response.setHeader('Location', '/');
        this.response.end('See ya');
    }


text:
Q: Text Tkinter Python 3.8 - Контекстное меню Хочу написать аналог блокнота Windows на Python с некоторыми добавлениями. Но как я могу реализовать вход в приложение по контекстному меню?
Поясню. Допустим, у меня есть файл file.txt, который я хочу отредактировать через моё приложение. Я хочу нажать по файлу ПКМ, и в контекстном меню этого файла выбрать "Редактировать с помощью <моё приложение>". Возможно ли это организовать?


text:
Q: Where is db:create defined in Rails? The following command is supposed to create a new database.

rails db:create

Where is this function defined? Or is this a pre-packaged function in rails?

A: It's in the databases.rake file of the framework:
namespace :create do
  task all: :load_config do
    ActiveRecord::Tasks::DatabaseTasks.create_all
  end

  ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name|
    desc "Create #{spec_name} database for current environment"
    task spec_name => :load_config do
      db_config = ActiveRecord::DatabaseConfigurations.config_for_env_and_spec(Rails.env, spec_name)
      ActiveRecord::Tasks::DatabaseTasks.create(db_config.config)
    end
  end
end

Whenever you doubt or want to know where a task has been defined, you can use the rails -W (or rake) command, passing the task:
$ rails -W db:create
rails db:create     /path/databases.rake:26:in `block in <top (required)>'
rails db:create:all /path/databases.rake:20:in `block (2 levels) in <top (required)>'

Note it was introduced in the version 0.9 of Rake. This might or might not work depending on the versions which you're working with.


text:
Q: Generated JSON in wrong format I have namedQuery defined in this manner
@NamedQuery(name = "Emp.findAll",
query = " select new test.entity.Emp(o.empNo, o.salary, p.projectId, p.projectName)
from Emp o inner join o.project p ")

In service class, I have
@GET
@Path("/projects")
@Produces(MediaType.APPLICATION_JSON)
public List<Emp> findAll() {
    return this.queryFindAll();

And generated JSON is this format
[{"empNo":"2390","empName":"JAMES","projects":{"projectId":209,"projectName":"Z560"}}]

Ideally I would like to generate JSON in the following format
[{"empNo":"2390","empName":"JAMES","projectId":"209","projectName":"Z560"}]

How can I do this?
Update 1
@GET
    @Path("/projects")
    @Produces(MediaType.APPLICATION_JSON)
    public Object findAll() throws IOException{
        String empAsJson = null;
        List<Emp> list = queryFindAll();
        ObjectMapper objectMapper = new ObjectMapper();
        empAsJson = objectMapper.writeValueAsString(list);
        return empAsJson;
    }

A: Looks like projects is getting serialized out as a map/object, you just need to make it an array of maps or objects.
Updated with pseudocode:
List<Map<String,String>> rolledupEmps = new ArrayList<Map<String,String>>();
for(Emp emp : emps){
     Map<String,String> em = mapper.readValue(emp, HashMap.class);
     em.put("projectId",em.get("projects")?!=null:em.get("projects").get("projectId"),"");
     em.put("projectName",em.get("projects")?!=null:em.get("projects").get("projectName"),"");
     em.remove(""projects"");
     rolledupEmps.put(em);
}
return mapper.writeValueAsString(rolledupEmps);


text:
Q: set room resource in Calendar App My G Suite has room resources set and I  can add resources to an event manually but not pro grammatically.  I cannot find any reference in the documentation,

A: If you are using the CalendarApp service this is quite straightforward, rooms have IDs that are very similar to email adresses, you have to invite these ressources just as you would invite guests.
It comes as optional parameter in the createEvent method in the form of an array of email adresses.
You will find these adresses in the agenda of each of these rooms (properties).


text:
Q: No me reconoce los endpoints en spring con mysql local Veréis estoy intentando hacer que mi microservicio de spring se conecte a una base de datos local. La cuestión es que se conecta pero los endpoints que pongo es como que no funciona.
Ahora mismo mi código está así:
Manager:
@Service
public class PerfilManager {

@Autowired
private PerfilRepository repository;

protected PerfilRepository getRepository() {
    return repository;
}

public List<PerfilEntity> getListaPerfiles(){
    return repository.findAll();
}}

Repository:
public interface PerfilRepository extends JpaRepository<PerfilEntity, Long> {}

Entity:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "perfil")
public class PerfilEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String nombre;

private String shortcut; }

DTO:
@Getter
@Setter
public class PerfilDTO {
    private Long id;

    private String nombre;

    private String shortcut;
}

Controller
public interface PerfilController {

    @FeignClient(FeignVariables.MICROSERVICE_ID)
    interface feign extends PerfilController {
    }

    @RequestMapping(method = RequestMethod.GET, value = "/listPerfiles")
    ResponseEntity<List<PerfilDTO>> listPerfiles();

}

CONTROLLER IMPL
@RestController
public class PerfilControllerImpl implements PerfilController {

    @Autowired
    private PerfilManager manager;

    @Override
    public ResponseEntity<List<PerfilDTO>> listPerfiles() {
        List<PerfilEntity> entityList = manager.getListaPerfiles();
        List<PerfilDTO> dtoList = new ArrayList<PerfilDTO>();

        if(entityList.size() != 0) {
            for(PerfilEntity perfil : entityList) {
                PerfilDTO pDTO = new PerfilDTO();
                pDTO.setId(perfil.getId());
                pDTO.setNombre(perfil.getNombre());
                pDTO.setShortcut(perfil.getShortcut());
                dtoList.add(pDTO);
            }
            return new ResponseEntity<List<PerfilDTO>>(dtoList, HttpStatus.OK);

        }   else {
            return new ResponseEntity<List<PerfilDTO>>(dtoList, HttpStatus.NO_CONTENT);
        }

    }

}

Vale. Esto es un ejemplo de todo mi codigo.
Como veis hago lo basico. El Feign Variables no lo pongo porque es solo una clase que devuelve el nombre del micro.
Ahora pongo lo de mi .properties:
spring.datasource.url=jdbc:mysql://localhost:3306/yufit
spring.datasource.username=root
spring.datasource.password=

## Hibernate Properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Lo dicho, se me conecta a la base de datos pero no recibo nada a cambio cuando pongo:
localhost:8080/perfil/listPerfiles
No se cual podria ser el error...
Este es lo que devuelve en consola:
    2019-07-24 17:32:48.913  INFO 7008 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-07-24 17:32:49.107  INFO 7008 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$649d9ac1] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-24 17:32:50.595  INFO 7008 --- [  restartedMain] o.d.ms.yufit.Yufit.YufitApplication      : No active profile set, falling back to default profiles: default
2019-07-24 17:32:51.844  INFO 7008 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-24 17:32:51.969  INFO 7008 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 44ms. Found 0 repository interfaces.
2019-07-24 17:32:52.239  INFO 7008 --- [  restartedMain] o.s.cloud.context.scope.GenericScope     : BeanFactory id=f663ecc1-3d85-3053-91c9-573eda8f067a
2019-07-24 17:32:52.409  INFO 7008 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$488397c4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-24 17:32:52.438  INFO 7008 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$649d9ac1] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-24 17:32:52.939  INFO 7008 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-24 17:32:53.000  INFO 7008 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-24 17:32:53.001  INFO 7008 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-24 17:32:53.213  INFO 7008 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-24 17:32:53.213  INFO 7008 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2609 ms
2019-07-24 17:32:53.728  INFO 7008 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-07-24 17:32:54.174  INFO 7008 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-07-24 17:32:54.416  INFO 7008 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-07-24 17:32:54.513  INFO 7008 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2019-07-24 17:32:54.515  INFO 7008 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-24 17:32:54.813  INFO 7008 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-24 17:32:55.290  INFO 7008 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-07-24 17:32:55.595  INFO 7008 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-24 17:32:55.613  WARN 7008 --- [  restartedMain] o.s.c.n.a.ArchaiusAutoConfiguration      : No spring.application.name found, defaulting to 'application'
2019-07-24 17:32:55.616  WARN 7008 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-07-24 17:32:55.616  INFO 7008 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-07-24 17:32:55.629  WARN 7008 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-07-24 17:32:55.629  INFO 7008 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-07-24 17:32:55.988  INFO 7008 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-24 17:32:56.060  WARN 7008 --- [  restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-07-24 17:32:56.373  INFO 7008 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-07-24 17:32:57.749  INFO 7008 --- [  restartedMain] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2019-07-24 17:32:58.024  INFO 7008 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-24 17:32:58.026  INFO 7008 --- [  restartedMain] o.d.ms.yufit.Yufit.YufitApplication      : Started YufitApplication in 10.728 seconds (JVM running for 14.23)

Saludos y espero que me ayudeis!

A: Spring boot por defecto está configurado para generar un JAR en lugar de un WAR (la aplicación no necesita un contenedor para ser desplegada), y por tanto generalmente (a menos que lo configures así) no necesitas poner el nombre de la aplicación en la URL, debería bastarte con
http://localhost:8080/listPerfiles

A: Me parece que hay un error en la ruta del endpoint, deberia ser
http://localhost:8080/listPerfiles
en lugar de
http://localhost:8080/perfil/listPerfiles

A: creo que tu error esta en la definición de tus clases, ya que spring reconoce como "endPointRest", los métodos que están bajo la etiqueta restController, por ende creo que esta demás hacer interface a perfil controller;
debería quedar algo asi.
@RestController
public class PerfilController {

        @FeignClient(FeignVariables.MICROSERVICE_ID)
        interface feign extends PerfilController {
        }

        @RequestMapping(method = RequestMethod.GET, value = "/listPerfiles")
        ResponseEntity<List<PerfilDTO>> listPerfiles();

}

la lógica de esta clase, por orden deberías crear otra clase de tipo service
algo así PerfilService, si quieres a esta clase le puedes hacer con interfaz lo cual también creo que esta demás,
saludos


text:
Q: sql join relationship - if an entry is found, then don't select I have 3 tables : users, roles and roles_users (roles_users is a relational table with 2 columns, user_id and role_id)
A user can have many roles, through the roles_users table.
How can I build a select query that will not select a user, if he has a specific role.
To illustrate :

*

*a super admin user has the super admin , admin, login and publisher roles.

*an admin user has the admin, login and publisher roles.

*a publisher user has the login and publisher roles.
I want to select all the users that do not have the super admin role.
In other words, if a user has the super admin role, then do not select it.
How can I achieve this in SQL ?
Edit : Here is the query that worked for me at the end : (thanks to András Ottó's answer)
SELECT DISTINCT(users.id), users.*
FROM users
INNER JOIN roles_users on users.id = roles_users.user_id
INNER JOIN roles ON roles_users.role_id = roles.id
WHERE NOT EXISTS(SELECT roles_users.user_id FROM roles_users
      WHERE roles_users.user_id = users.id AND roles_users.role_id = 2)

A: In Sql Server on in Oracle you can try:
SELECT users.*, roles.roleName
FROM users
INNER JOIN roles_users on users.userid = roles_users.userid
INNER JOIN roles ON roles_users.roleID = roles.roleID
WHERE NOT EXISTS(SELECT roles_users.userID FROM roles_users
      WHERE roles_users.userID = users.userid AND roleName = 'super admin')

Here is an SQL Fiddle.

A: Try this one,
it uses subquery
SELECT  a.*
FROM    users a
        INNER JOIN roles_use b
            on a.user_id = b.user_id
WHERE   b.role_id NOT IN
        (
            SELECT role_id
            FROM roles
            WHERE rolename = 'super admin'
        )

OR
uses left join
SELECT  a.*
FROM    users a
        LEFT JOIN roles_use b
            on a.user_id = b.user_id
        LEFT JOIN roles c
            ON b.role_id = c.role_id AND
               c.roleName = 'super admin'
WHERE   c.role_id IS NULL

A: You can simply use JOIN to get the solution to your problem....
If you have list of role to restrict, use NOT IN in following way:
SELECT a.* FROM users a INNER JOIN users_role b ON a.user_id= b.user_id
INNER JOIN roles c ON b.role_id = c.role_id
WHERE c.role_name NOT IN ('SUPER ADMIN')

If you have one role to restrict, use != in following way:
SELECT a.* FROM users a INNER JOIN users_role b ON a.user_id= b.user_id
INNER JOIN roles c ON b.role_id = c.role_id
WHERE c.role_name != 'SUPER ADMIN'

A: try something like this
SELECT  u.*
FROM    users u
JOIN    roles_users ru
ON      u.user_id=ru.user_id
JOIN    roles r
ON      r.role_id=ru.role_id
WHERE   rol_name !='Super admin'


text:
Q: ASP.NET MVC - Local Resource Issue I am having an issue when attempting to override the DisplayNameAttribute in ASP.NET MVC to provide a localized string. The code itself is straightforward and similar to that in another Stackoverflow post link text
The code works for global resources but not so well for local resources. I have a registration screen and used the Visual Studio "Generate Local Resource" command to create my local resource file. The generated file is named Registration.aspx.resx and the App_LocalResources folder is created relative to the actual Registration.aspx page - as one would expect.
However, when I attempt to get the localized string using:
ResourceManager.GetString(resourceKey)
I receive the following error message.

Could not find any resources
  appropriate for the specified culture
  or the neutral culture.  Make sure
  "FullAssemblyName.Views.Account.App_LocalResources.Registration_aspx.resources"
  was correctly embedded or linked into
  assembly "FullAssemblyName" at compile
  time, or that all the satellite
  assemblies required are loadable and
  fully signed.

Using reflector, I can see that the file is actually Registration.aspx.resources and not Registration_aspx.resources - the underscore/period being the subtle difference

FullAssemblyName.Views.Account.App_LocalResources.Registration.aspx.resources

I have toyed with the code quite a bit but no matter what I do, the file being requested is always different than that copiled in  the assembly. For instance, if i rename Registration_aspx (in the generated Registration.aspx.designer.cs class i get the same error but this time the path is "...App_LocalResources.Registrationaspx.resources"
Has anyone run into this? Is there any way I can ensure that the resource found in my assembly has this underscore?!?!?
Thank you in advance!

A: Try Michael K. Campbell solution link text. It worked fine form me in localizing my project.


text:
Q: Not able to Import import react-native-autocomplete-select in React Native App I want to use react-native-autocomplete-select for my project but when I am importing react-native-autocomplete-select it is giving an error .
Although problem is occuring when I am trying to import it. View is working perfectly fine when i am removing this import.
[Sat Aug 08 2020 14:49:42.581]  ERROR    TypeError: undefined is not an object (evaluating '_react.default.PropTypes.array')
[Sat Aug 08 2020 14:49:42.583]  ERROR    Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
[Sat Aug 08 2020 14:49:42.587]  ERROR    Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

I have tried installing and importing PropTypes
here is my View
import React,{useState} from 'react';
import {StyleSheet,View,Text,Button,TextInput} from 'react-native';
import {useNavigation} from '@react-navigation/native'
import PropTypes from 'prop-types';
import AutoComplete from 'react-native-autocomplete-select'

const suggestions = [
    {text: 'suggestion1', anotherProperty: 'value'},
    {text: 'suggestion2', anotherProperty: 'value2'}
  ]

function Other(){
    const navigation=useNavigation();
    const [input, setInput] = useState("")

    const onSelect = (suggestion) => {
        console.log(suggestion) // the pressed suggestion
      }

    return(
        <View style={styles.container}>
            <View style={styles.button}>
                <Button title="Menu" onPress={()=>{navigation.toggleDrawer()}} />
            </View>
            <View style={styles.view}>
              <TextInput
                style={styles.input}
                onChangeText={text=>setInput(text)}
                value={input}
                placeholder="text here..."
              />
            </View>
        </View>
    );
}

const styles=StyleSheet.create({
    container:{
        flex:1,
        justifyContent:'center',
        alignContent:'center'
    },
    button:{
        position:'absolute',
        top:10,
        right:10,
    },
    view:{
        padding:10,
        flex:1,
        marginTop:70
    },
    input:{
        height:50,
        borderColor:'#000',
        borderWidth:2,padding:10,
        borderRadius:5,
        fontSize:18
    }
});

export default Other;

please help me !!!And let me know if I am missing something here.

*

*"react": "16.13.1",

*"react-native": "0.63.2",

Thanks already.

A: OK, so I have solved this issue react-native-autocomplete-select uses an old react-native method i.e. React.PropTypes now with latest react they have removed PropTypes from react library So You have to edit react-native-autocomplete-select component here is the solution that you can use :-
first install prop-types
npm install --save prop-types

them make sure you have autocomplete select installed and go to your node_modules\react-native-autocomplete-select\AutoComplete\AutoComplete.js file
then do these changes
import React, { Component } from 'react'
import { TouchableHighlight, Text, TextInput, View } from 'react-native'
import stringScore from 'string_score'
import Styles from './Styles'
import PropTypes from 'prop-types';//import this

class AutoComplete extends Component {
    render(){
       return(
       .....
       )
    }
}
.....

//apply changes here
AutoComplete.propTypes = {
  suggestions:PropTypes.array,
  value:PropTypes.string,
  minimumSimilarityScore:PropTypes.number,
  comparationFuzziness:PropTypes.number,
  suggestionObjectTextProperty:PropTypes.string,
  onChangeText:PropTypes.func,
  onSelect:PropTypes.func.isRequired,
  suggestionsWrapperStyle:PropTypes.any,
  suggestionStyle:PropTypes.any,
  suggestionTextStyle:PropTypes.any,
  style:PropTypes.any,
  inputStyle:PropTypes.any,
}

AutoComplete.defaultProps = {
  minimumSimilarityScore: 0.6,
  comparationFuzziness: 0.5
}

export default AutoComplete

that's all now use this package as you want to!!


text:
Q: Solaris SMF Syntax I'm trying to write a SMF manifest but i'm stuck because i can't find the complete documentation. Their DTD (/usr/share/lib/xml/dtd/service_bundle.dtd.1) is a joke, it's full of CDATA.
For instance, i'm looking for the complete specification for <service_fmri/>, which value attributes are valid, etc.
Where can i find the complete specification for writing Solaris SMF manifests ?
Thanks.

A: The DTD looks fine on my system.  The only attribute to service_fmri is "value".
<!--
  service_fmri

    This element defines a reference to a service FMRI (for either a
    service or an instance).

    Its attribute is

        value   The FMRI.
-->

<!ELEMENT service_fmri EMPTY>

<!ATTLIST service_fmri
        value           CDATA #REQUIRED>

Oh...I see you wanted what are valid FMRI values.  Start at the smf(5) man page for that kind of reference.


text:
Q: tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint I am trying to run the following script, to train a network and use it to predict. I use python 3.6.3 and tf 1.6.
'''Used for training and predicting a convolutional neural net with two 9 node
output layers. Does not use batch normalization'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import random
import pickle
import tensorflow as tf
import codecs
import os
import datetime

truth_values=['mchi','chi','ek','ph','ts','tr','trph','tw','ltr','tsek','noise']
tf.logging.set_verbosity(tf.logging.INFO)

def input_function(xs1,xs2, labels,labels2, batch_size,i):
    """An input function for training,creates a minibatch of batch_size from input data"""
    length=np.shape(xs1)[0]
    #numb gives the number of next batch to be used given i
    numb=i%(length//batch_size)
    new_features={}
    #randomizes which input goes to which channel
    if random.random()>0.5:
        change={'x':'x','x2':'x2'}
        new_features['y']=labels[batch_size*numb:batch_size*(numb+1)]
        new_features['y2']=labels2[batch_size*numb:batch_size*(numb+1)]
    else:
        change={'x':'x2','x2':'x'}
        new_features['y']=labels2[batch_size*numb:batch_size*(numb+1)]
        new_features['y2']=labels[batch_size*numb:batch_size*(numb+1)]
    for key in ['x','x2']:
        new_features[key]=[]

    '''randomly rolls each pair of spectrograms in the batch for up to 5 pixels
    horizontally and vertically. Roll amount is same for both spectrograms'''

    for i in range(batch_size*numb,batch_size*(numb+1)):
        ver_shift=random.randint(-5,5)
        hor_shift=random.randint(-5,5)
        a=np.roll(xs1[i],(ver_shift,hor_shift),axis=(0,1))
        new_features[change['x']].append(a)

        a2=np.roll(xs2[i],(ver_shift,hor_shift),axis=(0,1))
        new_features[change['x2']].append(a2)

    for key in new_features.keys():
        new_features[key]=np.array(new_features[key],dtype=np.float32)
    return new_features

def eval_input_function(xs1,xs2, labels,labels2, batch_size,i):
    """An input function for evaluation, same as input_function() but doesn't use
    randomization"""
    length=np.shape(xs1)[0]
    numb=i%(length//batch_size)
    new_features={}
    new_features['y']=labels[batch_size*numb:batch_size*(numb+1)]
    new_features['y2']=labels2[batch_size*numb:batch_size*(numb+1)]
    for key in ['x','x2']:
        new_features[key]=[]
    for i in range(batch_size*numb,batch_size*(numb+1)):
        new_features['x'].append(xs1[i])
        new_features['x2'].append(xs2[i])

    for key in new_features.keys():
        new_features[key]=np.array(new_features[key],dtype=np.float32)
    return (new_features)

def pred_input_function(xs1,xs2, i):
    """An input function for predictions, makes a minibatch of 50
    spectrograms with step size of 50ms"""

    new_features={}
    for key in ['x','x2']:
        new_features[key]=[]
    '''splits 257x1299 array into 50 separate 257x256 pieces, 50ms stepsize translates to
    1299/50~26 pixels step size. First 41 pieces can be sliced from the first spectrogram array
    while the other 9 have to be concatenated with the first parts of the next array'''
    for j in range(41):
      start=26*j
      a=xs1[i,:,start:start+256]
      new_features['x'].append(a)

      a=xs2[i,:,start:start+256]
      new_features['x2'].append(a)

    for k in range(9):
      start=26*(k+41)
      init_a=xs1[i,:,start:]
      last=256-np.shape(init_a)[1]
      a=np.concatenate([init_a,xs1[i+1,:,:last]],axis=1)
      new_features['x'].append(a)

      init_a=xs2[i,:,start:]
      a=np.concatenate([init_a,xs2[i+1,:,:last]],axis=1)
      new_features['x2'].append(a)
    for key in new_features.keys():
      new_features[key]=np.array(new_features[key],dtype=np.float32)
    return new_features

def main(xs1=None,xs2=None, batch_size=10, mode='predict', model_dir='Models/model.ckpt'):
  '''the main function for using the network,
  -xs1 and xs2 are used to feed input files when in prediction mode,
  -batch_size refers to the minibatch size to be used when training,
  higher batch_size makes the network train faster but also use more memory, batch_size for predictions is
  hard coded to 50 due to more complicated data structure for performance gains.
  -mode tells whether the network is predicting or training, should be one of 'train' and 'predict'
  -model_dir is the path to where the model should be saved/loaded from'''
  #loads training data, done here to minimize memory usage
  if mode=='train':
      fil_tr_x1=open('Data/train_xs1','rb')
      xs1=np.load(fil_tr_x1)
      fil_tr_x1.close()
      fil_ev_x1=open('Data/eval_xs1','rb')
      eval_xs1=np.load(fil_ev_x1)
      fil_ev_x1.close()

      fil_tr_x2=open('Data/train_xs2','rb')
      xs2=np.load(fil_tr_x2)
      fil_tr_x2.close()
      fil_ev_x2=open('Data/eval_xs2','rb')
      eval_xs2=np.load(fil_ev_x2)
      fil_ev_x2.close()

      fil_tr_y=open('Data/train_ys_single','rb')
      labels=np.load(fil_tr_y)
      fil_tr_y.close()
      fil_ev_y=open('Data/eval_ys_single','rb')
      eval_labels=np.load(fil_ev_y)
      fil_ev_y.close()

      fil_tr_y2=open('Data/train_ys_single2','rb')
      labels2=np.load(fil_tr_y2)
      fil_tr_y2.close()
      fil_ev_y2=open('Data/eval_ys_single2','rb')
      eval_labels2=np.load(fil_ev_y2)
      fil_ev_y2.close()

  """Creates the two stream convolutional neural net with 4 blocks of conv-conv-maxpool"""
  # Input Layer
  x = tf.placeholder(tf.float32, [None, 257, 256])
  input_layer=tf.reshape(x,[-1,257,256,1])
  pool0 = tf.layers.max_pooling2d(inputs=input_layer, pool_size=[2, 2], strides=2)

  conv1 = tf.layers.conv2d(
      inputs=pool0,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv2 = tf.layers.conv2d(
      inputs=conv1,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool1 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  conv3 = tf.layers.conv2d(
      inputs=pool1,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv4 = tf.layers.conv2d(
      inputs=conv3,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool2 = tf.layers.max_pooling2d(inputs=conv4, pool_size=[2, 2], strides=2)#64,52

  conv5 = tf.layers.conv2d(
      inputs=pool2,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv6 = tf.layers.conv2d(
      inputs=conv5,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool3 = tf.layers.max_pooling2d(inputs=conv6, pool_size=[2, 2], strides=2)  #128,105

  conv7 = tf.layers.conv2d(
      inputs=pool3,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv8 = tf.layers.conv2d(
      inputs=conv7,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool4 = tf.layers.max_pooling2d(inputs=conv8, pool_size=[2, 2], strides=2)

  #Second convolutional stream for second input
  x2=tf.placeholder(tf.float32,[None,257,256])
  input_layer2 = tf.reshape(x2, [-1, 257, 256, 1])

  pool02 = tf.layers.max_pooling2d(inputs=input_layer2, pool_size=[2, 2], strides=2)

  conv12 = tf.layers.conv2d(
      inputs=pool02,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv22 = tf.layers.conv2d(
      inputs=conv12,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool12 = tf.layers.max_pooling2d(inputs=conv22, pool_size=[2, 2], strides=2)

  conv32 = tf.layers.conv2d(
      inputs=pool12,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv42 = tf.layers.conv2d(
      inputs=conv32,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool22 = tf.layers.max_pooling2d(inputs=conv42, pool_size=[2, 2], strides=2)

  conv52 = tf.layers.conv2d(
      inputs=pool22,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv62 = tf.layers.conv2d(
      inputs=conv52,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool32 = tf.layers.max_pooling2d(inputs=conv62, pool_size=[2, 2], strides=2)

  conv72 = tf.layers.conv2d(
      inputs=pool32,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv82 = tf.layers.conv2d(
      inputs=conv72,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool42 = tf.layers.max_pooling2d(inputs=conv82, pool_size=[2, 2], strides=2)

  # Combines the two convolutional nets and reshapes them into 1D(excluding batch dimension)
  final_pool_flat = tf.concat([tf.reshape(pool4, [-1, 8 * 8 * 64]),
                               tf.reshape(pool42, [-1, 8 * 8 * 64])],axis=1)
  #adds a 1024 fully connected layer with droupout
  dense = tf.layers.dense(inputs=final_pool_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == 'train')
  #Creates the two output layers(logits, logits2)
  logits = tf.layers.dense(inputs=dropout, units=9)
  logits2= tf.layers.dense(inputs=dropout, units=9)
  #placeholders for labels
  y=tf.placeholder(tf.float32,[None,9])
  y2=tf.placeholder(tf.float32,[None,9])

  classes=tf.argmax(logits, axis=1)
  classes2=tf.argmax(logits2, axis=1)
  correct=tf.argmax(y, axis=1)
  correct2=tf.argmax(y2, axis=1)
  accuracy=tf.logical_and(tf.equal(classes,correct),tf.equal(classes2,correct2))

  probabilities=tf.nn.softmax(logits, name="softmax_tensor")
  probabilities2=tf.nn.softmax(logits2, name="softmax_tensor")

  loss1 = tf.losses.softmax_cross_entropy(onehot_labels=y, logits=logits)
  loss=loss1+tf.losses.softmax_cross_entropy(onehot_labels=y2, logits=logits2)
  lr=0.0003
  lrate=tf.placeholder(tf.float32,None)
  optimizer = tf.train.AdamOptimizer(learning_rate=lrate,epsilon=0.001)

  #needed if using batch normalization to make sure it works properly
  update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  with tf.control_dependencies(update_ops):
    train_step = optimizer.minimize(loss)

  sess = tf.InteractiveSession()
  saver = tf.train.Saver()
  #if in prediction mode will use a saved model but if in train mode will train a new model instead
  if mode=='predict':
      saver.restore(sess, model_dir)
      print('Model restored')
  else:
      print('Training new model')
      tf.global_variables_initializer().run()

  if mode == 'predict':
    preds_list=[]
    preds_list2=[]
    predictions=[]
    predictions2=[]
    print('Predicting')
    length=min(np.shape(xs1)[0],np.shape(xs2)[0])
    num_batches=length
    for i in range(num_batches-1):
        inputs=pred_input_function(xs1,xs2, i)
        preds,preds2=sess.run([probabilities,probabilities2],feed_dict={x:inputs['x'],x2:inputs['x2']})
        for j in range(len(preds)):
            preds_list.append(preds[j])
            preds_list2.append(preds2[j])
        if i%25==0:
            print('{}/{}'.format(i,num_batches))
    '''After getting predictions for each timestep, makes final lists(predictions,predictions2)
    by averaging across 5 consecutive predictions,(step size of 1)'''

    for i in range(len(preds_list)-4):
        mean_preds=np.mean(preds_list[i:i+5],axis=0)
        mean_preds2=np.mean(preds_list2[i:i+5],axis=0)
        predictions.append(mean_preds)
        predictions2.append(mean_preds2)

    print(np.shape(predictions))
    tf.Graph()
    sess.close()
    return predictions,predictions2

  if mode=='train':

    length=np.shape(xs1)[0]
    s=[]
    accuracies=[]
    for j in range(length):
        s.append(j)
    for i in range(200):
        numb=i%(length//batch_size)
        #shuffles training data after a full epoch
        if numb==0:
            random.shuffle(s)
            labels=labels[s]
            labels2=labels2[s]
            xs1=xs1[s]
            xs2=xs2[s]

        inputs=input_function(xs1,xs2, labels,labels2, batch_size,i)
        #trains the model while keeping track of accuracy
        _,accurs=sess.run([train_step,accuracy],feed_dict={x:inputs['x'],x2:inputs['x2'],
                                                           y:inputs['y'],y2:inputs['y2'],lrate:lr})
        for value in accurs:
            if value==True:
                accuracies.append(1)
            else:
                accuracies.append(0)
        #prints training accuracy and evaluates evaluation accuracy every 1000 steps
        #also multiplies learning rate by 0.97
        if i%100==0:
            print("Step {} Train accuracy: {:.4f}".format(i,np.mean(accuracies)))
            mode='eval'
            lr=lr*0.97
            accuracies=[]
            for k in range(np.shape(eval_xs1)[0]//batch_size):
                inputs=eval_input_function(eval_xs1,eval_xs2, eval_labels,eval_labels2, batch_size,k)
                accurs=sess.run(accuracy,feed_dict=
                        {x:inputs['x'],x2:inputs['x2'],y:inputs['y'],y2:inputs['y2']})
                for value in accurs:
                    if value==True:
                        accuracies.append(1)
                    else:
                        accuracies.append(0)
            mode='train'
            print("Eval accuracy: {:.4f}".format(np.mean(accuracies)))
            accuracies=[]
            savepath=saver.save(sess, model_dir)
            print('Model saved', savepath)

def train(model_dire):
  main(batch_size=25,mode='train',model_dir=model_dire)

def predict(pred_data1,pred_data2,predictions_file1,predictions_file2,model_dir):
    '''function for predicting with the network
    -pred_data1 is the path to first file containing spectrogram arrays for file to be predicted from
    -pred_data2 is the path to second input file from the same session,
    if none an array of zeroes will be fed as the second input
    -predictions_file1 and predictions_file2 are the paths to where predictions will be saved,
    -model_dir is the path to the saved model to be used for predicting'''
    fil1=open(pred_data1,'rb')
    predict_x1=np.load(fil1)
    fil1.close()
    if pred_data2!=None:
        fil2=open(pred_data2,'rb')
        predict_x2=np.load(fil2)
        fil2.close()
    else:
        predict_x2=np.zeros(np.shape(predict_x1),dtype=np.float16)

    predictions1,predictions2=main(predict_x1,predict_x2,batch_size=25,mode='predict',
                     model_dir=model_dir)

    np.save(predictions_file1,predictions1)
    np.save(predictions_file2,predictions2)

if __name__=='__main__':
  start=datetime.datetime.now()
  train("Models/model_small.ckpt")
  print("Time taken: ", datetime.datetime.now()-start)
  predict('Data/Selma_111722_aligned_x1_test',
          'Data/Kafka_111722_aligned_x2_test',
          'Data/pred_111722_Selma_model_small',
          'Data/pred_111722_Kafka_model_small',
          model_dir="Models/mode_small.ckpt")

But I get the following error:
INFO:tensorflow:Restoring parameters from Models/model_small.ckpt
2022-12-12 15:46:26.678180: W C:\tf_jenkins\workspace\rel-win\M\windows\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key beta1_power_1 not found in checkpoint
Traceback (most recent call last):
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1361, in _do_call
    return fn(*args)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _run_fn
    target_list, status, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 516, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "new_train_72.py", line 437, in <module>
    model_dir="Models/model_small.ckpt")
  File "new_train_72.py", line 423, in predict
    model_dir=model_dir)
  File "new_train_72.py", line 315, in main
    saver.restore(sess, model_dir)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1755, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
    run_metadata_ptr)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1137, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1355, in _do_run
    options, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1374, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

Caused by op 'save_1/RestoreV2', defined at:
  File "new_train_72.py", line 437, in <module>
    model_dir="Models/model_small.ckpt")
  File "new_train_72.py", line 423, in predict
    model_dir=model_dir)
  File "new_train_72.py", line 312, in main
    saver = tf.train.Saver()
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1293, in __init__
    self.build()
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1302, in build
    self._build(self._filename, build_save=True, build_restore=True)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1339, in _build
    build_save=build_save, build_restore=build_restore)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 796, in _build_internal
    restore_sequentially, reshape)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 449, in _AddRestoreOps
    restore_sequentially)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 847, in bulk_restore
    return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 1113, in restore_v2
    shape_and_slices=shape_and_slices, dtypes=dtypes, name=name)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3271, in create_op
    op_def=op_def)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1650, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

NotFoundError (see above for traceback): Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

I checked what is saved in my checkpoint (using inspect_checkpoint), and there are only beta1_power and beta2_power.
Also, when I run only the train part alone, or the predict part alone (by commenting lines 431 or 433) I do not get an error, but the prediction completely fails (does not detect anything).
Is there something wrong with the saving/restoring of the model? Why is it not working when I run the whole script (train and predict)? And why do I have no errors but no results when I run them separately?
Thanks for reading!