text:
Q: Stutter while gaming every 3-4 seconds in Windows using MacBook Pro 2012 (MacBook 9.1) using Windows 7 I'm using Windows with Bootcamp on my Mid-2012 MacBook Pro (Here is the config). Recently when I play a game, I get frequent (and somewhat constant) stutter every 2-3 seconds, no matter if it's a 2D or 3D game, no matter if I lower the graphic and resolution.
I've searched extensively in the past few days and finally went to ask it here. Things I've tried so far:

*

*GPU-Z shows GPU temprature of around 90 C when I have the stutter.

*In Process Explorer, I can see that GPU usage is 100%, even in lowest graphic settings of low resolution of a not-AAA game. (Lara Croft and Temple of Osiris for example and Ori and The Blind Forest)

*I've updated my nVidia drivers to the latest.

*I've uninstalled everything nVidia related and installed them again.

*I've disabled Audio and Network drivers (as I've read they can cause stutter in cases).

*I've tried DPC Latency Checker and mostly I see a spike when I observe a delay.

I'm very afraid to have hardware fault since where I live, we don't have Apple stores.
Also I've installed DS3 Driver to attach a PS3 controller to my PC, even though the controller was not attached during the tests, this might've affected the performance since I've read that stutter is caused by a driver having problem doing it's task on proper time frame.
Any help is appreciated.

A: The temperature 90° C might be the limit for your GPU where it starts "throttling", i.e. halts for a bit to cool down. Or maybe the CPU using the same heatpipes/sink hits its limit. How high does the CPU temp go? (CPU-Z) and what specific CPU model does that MacBook have?
Put something small under the laptop to prod it up giving it more room to breathe or use some active cooling pad with USB-powered fans and see if there are less freezes

A: See https://forums.anandtech.com/threads/gpu-throttling-on-macbook-pro-9-1-mostly-solved.2333625/.
In my case, ThrottleStop showed the CPU as running at 3.4GHz constantly, averaging 90C. Disabling Turbo (in ThrottleStop) reduced it to 2.6GHz and 70C. I don't know if the culprit was power or heat, but after making the change the GPU seems happier and the stuttering is gone.


text:
Q: Binding a UDP socket to wildcard hosts in Ruby I have been trying to understand the basic idea behind UDP hole punching, and I'm having trouble understanding the difference between the following two socket bindings:
 sock = UDPSocket.new
 sock.bind('', port )

and
sock = UDPSocket.new
sock.bind('0.0.0.0', port)

Previously I had thought using '' or '0.0.0.0' did the same thing -- allow the socket to listen on any network interface -- but since the code didn't work with them interchanged I must be missing something.
For the initial 'punch' the datagram is sent from a socket bound to '', which is then closed and the actual communication with the remote host is done over a socket bound to 0.0.0.0. I know 0.0.0.0 generally refers to the default route, but I can't figure out the significance of that in this situation. Does binding a socket to 0.0.0.0 mean you're assigning it the address of the default gateway?

A: Looks like both provides the same behavior: your socket is listening on all interfaces on given port:
ruby      38156 grych    7u  IPv4 0x40a92a845129cab1      0t0  UDP *:6666

My system is Darwin 14.0 (OS X Mavericks), ruby 2.0.0 - I am wondering if it depends on the OS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dialog box after animation going to top I am making a custom dialog box which will pop up using animation from bottom to centre. everything is fine but after the animation dialog box is going to the top of the screen. I want it to be in centre only. Here is my code .
 public class CustomDialogClass extends Dialog implements
    android.view.View.OnClickListener {

    public Activity c;
    public Dialog d;
    public Button yes, no;
    private Animation mAnimationBottomCentre;

    public CustomDialogClass(Activity a) {
    super(a,R.style.DialogAnimation);
    // TODO Auto-generated constructor stub
    this.c = a;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dialog_view);

//  LinearLayout ll = (LinearLayout) findViewById(R.id.mainlayout);
//  mAnimationBottomCentre = AnimationUtils.loadAnimation(c, R.anim.slide_in_left);
//  ll.startAnimation(mAnimationBottomCentre);
    yes = (Button) findViewById(R.id.btn_yes);
    no = (Button) findViewById(R.id.btn_no);
    yes.setOnClickListener(this);
    no.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_yes:
        c.finish();
        break;
    case R.id.btn_no:
        dismiss();
        break;
    default:
        break;
    }
    dismiss();
    }
}

I am calling dialog box from my activity like this:
 public void Show_Dialog(View v) {
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.getWindow().getAttributes().windowAnimations = com.example.chintan.khetiya.android.custom_dialog.R.style.DialogAnimation;
cdd.getWindow().setGravity(Gravity.CENTER);
cdd.show();
}

this is my anim file
    <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/decelerate_interpolator" >
  <translate
        android:duration="2000"
        android:fillAfter="true"
        android:fromYDelta="100%p"
        android:startOffset="100"
        android:toYDelta="50%p" />
  </set>

and this is style xml
    <style name="DialogAnimation">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowEnterAnimation">@anim/slide_up_bottom_to_centre</item>
</style>

Layout for dialog
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:id="@+id/mainlayout"

    android:layout_height="80dp"
    android:background="#E60000"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold" >
    </TextView>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

can somebody please help how to show dialog after animation in centre only

A: Check this:

*

*http://android-er.blogspot.in/2012/07/dialog-animation-using-windowanimations.html

*http://www.techrepublic.com/blog/software-engineer/add-custom-transitions-to-android-alert-dialogs/

*Animate a custom Dialog


text:
Q: Why is $e^{-i\theta} = \cos \theta -i\sin \theta$? Yeah. I probably just missed it in lecture, but I totally missed why this is like this. Sorry. Thanks.
A part of me wants to understand it as
$$e^{-i\theta} = \cos (-\theta) + i\sin (-\theta)$$
But idk

A: Hint: the $\cos$ function is even and $\sin$ function is odd:
$$\cos (-\theta)=\cos \theta.$$
$$\sin (-\theta)=-\sin \theta.$$

A: Assuming that $e^z$ is defined as $\sum\limits_{n=0}^{\infty}\frac{z^n}{n!}$ (remember that there are a few ways of defining $e$), we have:
$$e^{i\theta}:=1+i\theta+\frac{\theta^2i^2}{2!}+\frac{\theta^3i^3}{3!}+\frac{\theta^4i^4}{4!}+\frac{\theta^5i^5}{5!}+\cdots=$$
Knowing $i = \sqrt{-1}, i^2 = -1, i^3=-i, i^4 =1$
We can simplifying our formula $$\boxed{e^{i\theta}\equiv1+i\theta-\frac{\theta^2}{2!}-\frac{i\theta^3}{3!}+\frac{\theta^4}{4!}+\frac{i\theta^5}{5!}-\cdots}$$
Now, $\color{blue}{\underbrace{\cos(\theta)=1-\frac{\theta^2}{2!}+\frac{\theta^4}{4!}-\frac{\theta^6}{6!}+\cdots}_{\text{Taylor expansion of} \cos(\theta)}}$.
Also, $\underbrace{\sin(\theta)=\theta-\frac{\theta^3}{3!}+\frac{\theta^5}{5!}-\frac{\theta^7}{7!}+\cdots}_{\text{Taylor expansion of} \sin(\theta)}\iff \color{green}{i\sin(\theta)=i\theta-\frac{i\theta^3}{3!}+\frac{i\theta^5}{5!}-\frac{i\theta^7}{7!}+\cdots}$.
Now, $\color{blue}{\cos(\theta)}\color{\green}{+i\sin(\theta)}=\color{blue}{1}\color{green}{+i\theta}\color{blue}{-\frac{\theta^2}{2!}}\color{green}{-\frac{i\theta^3}{3!}}\color{blue}{+\frac{\theta^4}{4!}}\color{green}{+\frac{i\theta^5}{5!}}\color{blue}{-}\cdots=e^{i\theta}$.

A: My understanding of your question, before it got edited,
was how we get $e^{-i\theta}=\cos\theta-i\sin\theta$ from $e^{i(-\theta)}=\cos(-\theta)+i\sin(-\theta)$.
The answer is that $\cos(-\theta)=\cos(\theta)$ and $\sin(-\theta)=-\sin(\theta)$
(cosine is an even function, and sine is an odd function).


text:
Q: When/how is the "memoryview()" function used? I came across it in my autocomplete when I started typing the name of a variable that began with m, what is it used for and when/how should it be used?

A: memoryview() exposes the buffer protocal of an object. Buffers are internal memory arrays. You can use memoryview() to access large pieces of data without having to copy the data, which can be memory-intensive.
Edit: To further explain, when you know the memory address of an object, you can simply set another object equal to that memory address


text:
Q: Wpf - MVVM and Service in separate assemblies or folder I found many tutorial. In each View / ViewModel / Model and Service use folder. But, can I separate them in assemblies ?
For example:
Core

*

*ViewCore.dll (reference ViewModel)

*ViewModelCore.dll (reference Model & Service)

*ServiceCore.dll

Module A

*

*ViewModuleA.dll (reference ViewCore)

*ViewModelModuleA (reference ViewModelCore)

*ModelModuleA.dll

*ServiceModuleA.dll (reference ModelModuleA + ServiceCore)

Other

*

*Startup.exe (reference all dll + init service etc.)

What is the best way in C# / WPF ? Separate in different folder or assemblies ?
Thanks.

A: Just put them in separate projects.
Example:
Add a Class library project named: ViewModuleA, will result in ViewModuleA.dll
then you just reference the class library project, to the startup project, and import namespaces where needed.


text:
Q: Ansible playbook to check a file in the particular location until the file has been created by a process/manually The real scenario is,
I have to keep on check a particular location to check a file(created by another service) is exist or not until I stopping the ansible-playbook script manually.
but the script has to check all the hosts until I stopping the script. also, it has to print the message that either file exists or not continuously for each host.
I tried to write the playbook by using the below code which checks file location only one time(obviously).
  tasks:
- name: checking the flag in /path/to/file directory.
  stat:
    path: /path/to/the/file
  register: file_name
- name: Report if file exists
  debug:
    msg: 'Exception occured {{ inventory_hostname }}'
  when: file_name.stat.exists
- name: Report if file not exists
  debug:
    msg: 'ATF still running {{ inventory_hostname }}'
  when: not file_name.stat.exists

A: maybe you can use until to check for the status of the file:
- name: checking the flag in /home/dev/ATF/ directory.
  stat:
    path: /path/to/the/file
  register: file_name
  until: file_name.stat.exists is not false
  retries: 10
  delay: 5


text:
Q: Verifone Printer Api (library) according to verifone's documentationVerifone Printer Api
the developer only needs to define this on build.gradle
dependencies {
   compile (name: 'DeveloperSDK-release.x.x.x', ext: 'aar')
}

I did what the documentation said, I have a CommercePlugin installed in my studio Downloaded their SDK, followed the steps, still no luck,
I even tried to manually copy paste the Carbon Api's aar, rename it, still no luck.
Do I have to request their Printer AAR file?
Any related experience here?


text:
Q: Could I retrieve the accessibility to Google Colaboratory after the usage limitation? According to Google's FAQ webpage, Google often hampers heavy users from using GPU and TPU at Google Colaboratory. I think that I ran into trouble due to this reason. However, the document does not state whether users who Google regulated can reuse this service. If you know about the issue, please share your experience. Thank you.

A: For reference, I post my experience here. Though I could not use Google Colab at that time, the constraint was released after one day.


text:
Q: WSO2- Error Using Clone Mediator to send message to an endpoint I am working on WSO2 proxy service that invokes a lot of other DSS services. My requirement is to send the response of one of the DSS service on to a jms queue and at the same time continue with the exsiting flow in the proxy service i.e. continue invoking and processing the other DSS services.
I need to get the response of Simple Product Service (sequence key -if4_simpleProduct) and send it back on to the queue, but after that continue with logic that is placed in the proxy service and sequence. I tried using CLONE Mediator for the same. But my prxy service flow stops after coming in to the CLONE Meditaor flow. Below is the snippet for proxy service and sequence.
    <?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse" name="SPE_Payload"
    transports="jms" startOnLoad="true" trace="enable">
    <description />
    <target>
        <inSequence>
            <transaction action="new" />
            <xslt key="StepToCommon" />
            <log level="full" />
            <enrich>
                <source type="body" clone="true" />
                <target type="property" property="MSG_PAYLOAD" />
            </enrich>

            <sequence key="if4_simpleProduct" />

            <filter xpath="boolean (//product/simpleProduct/altPrdCodes/pn_apc_id/text())">
                <enrich>
                    <source clone="true" xpath="//product/simpleProduct/altPrdCodes" />
                    <target type="property" property="ALT_PRDS" />
                </enrich>
                <sequence key="if4_alternateProducts" />
            </filter>
....
.....

<transaction action="commit" />
        </inSequence>

    </target>
    <parameter name="transport.jms.ContentType">application/xml</parameter>
    <parameter name="transport.jms.Destination">test</parameter>
</proxy>

Given below is the code of for sequence while calling Simple Product Service
<sequence xmlns="http://ws.apache.org/ns/synapse" name="if4_simpleProduct"
    onError="myErrorHandlerSeq">
    <payloadFactory>
        <format>
            <p:O_SimpleProduct xmlns:p="http://ws.wso2.org/dataservice">
                <p:PC_STEP_SKU_ID>$1</p:PC_STEP_SKU_ID>
                </p:O_SimpleProduct>
        </format>
        <args>
            <arg xmlns:m="http://wso2.org/services/product" evaluator="xml"
                expression="//product/simpleProduct/step_id/text()" />
        </args>
    </payloadFactory>
    <header name="Action" value="urn:O_SimpleProduct" />
    <callout serviceURL="local://localhost/services/productEnrichment"
        action="urn:O_SimpleProduct" useServerConfig="true">
        <source xmlns:ns="http://org.apache.synapse/xsd" xpath="$body/child::*[fn:position()=1]" />
        <target xmlns:ns="http://org.apache.synapse/xsd" xpath="$body/child::*[fn:position()=1]" />
    </callout>
    <clone sequential="false">
<property name="RESPONSE" value="true" />
    <header name="To" action="remove" />
      <target>
      <endpoint>
            <address
                uri="jms:/step.IF04Output?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=queue" />
        </endpoint>
        </target>

      <target>
    <filter xmlns:ns="http://org.apache.synapse/xsd" xmlns:ds="http://wso2.org/services/product"
        source="//ds:result/ds:set/ds:PC_STATUS/text()" regex="0">
        <then>
            <log level="custom">
                <property name="STATUS"
                    value="************DONE INSERTING SIMPLE ATTRIBUTES***************" />
            </log>
        </then>
        <else>
            <log level="full" category="ERROR">
                <property name="STATUS"
                    value="************ERROR OCCURED WHILE INSERTING SIMPLE ATTRIBUTES. ROLLBACKING THE TRANSACTION***************" />
                <property name="PC_RP_ID" expression="get-property('GEN_RP_ID')" />
            </log>
            <transaction action="rollback" />
            <drop />
        </else>
    </filter>
    <property xmlns:ds="http://wso2.org/services/product" name="GEN_RP_ID"
        expression="//ds:result/ds:set/ds:PC_RP_ID/text()" />
    <enrich>
        <source type="property" clone="true" property="MSG_PAYLOAD" />
        <target type="body" />
    </enrich>
    </target>
</clone>
</sequence>

I am struggling with the issue since last two days. tried sing Clone meditior in several places. but it does not work. Could you please provide your suggestions soon as I have a demo to go tomorrow and I need to sort it out :(
Cheers,
Aanchal

A: I think this is the part you are struggling;
<callout serviceURL="local://localhost/services/productEnrichment"
        action="urn:O_SimpleProduct" useServerConfig="true">
        <source xmlns:ns="http://org.apache.synapse/xsd" xpath="$body/child::*[fn:position()=1]" />
        <target xmlns:ns="http://org.apache.synapse/xsd" xpath="$body/child::*[fn:position()=1]" />
    </callout>
    <clone sequential="false">
<property name="RESPONSE" value="true" />
    <header name="To" action="remove" />
      <target>
      <endpoint>
            <address
                uri="jms:/step.IF04Output?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=queue" />
        </endpoint>
        </target>

Since your requirement is get response form one of the DS service and send that to queue..I think it fails because you are removing "To" header..Use callout mediator inside clone mediator's one of the "Target" configuration after sending to JMS queue drop the message there..In the other target, define your rest of the logic..


text:
Q: Problema para importar un archivo JS Estoy trabajando en un proyecto personal en el cual tengo varias paginas que son practicamente iguales. Por esta razon decidi trabajar con template y me cree una cabecera y un footer(De la mitad del cuerpo de la pagina para abajo) que serán reutilizados por todas mis paginas. Así optimizo y cualquier cambio que desee hacer solo lo tendré que hacer en un solo lugar.
Mi problema es el siguiente: Hasta este momento las funcionalidades que necesitaba estaban todos en un archivo js, el cual yo lo importo en mi plantilla footer ya que es el archivo js que utilizan todas mis pagina pero ahora mismo una de esas paginas necesita una funcionalidad adicional que no tienen las otras y necesito hacerlo en un nuevo archivo js. El problema es que no sé donde importar a dicho archivo.
Recuerden que esta pagina solo es un pedazo de codigo que no tiene ni cabecera ni de la mitad del cuerpo para abajo. Espero me hayan entendido. Así se ve la pagina a la cual necesito ponerle mi funcionalidad:
<?php
    session_start();
    if (!isset($_SESSION["user_id"])) {
        header("location:index.php");
    }
    include 'Templates/cabecera.php';
    ?>

    <ion-icon name="person"></ion-icon>
    <?php echo "Hi, ".$_SESSION["first_name"]  ?>

    <ion-icon name="cart" class="iconos_navBar"></ion-icon>
        Carrito

    <ion-icon name="create" class="iconos_navBar"></ion-icon>
        Cambiar contraseña

    <ion-icon name="log-out" class="iconos_navBar"></ion-icon>
        Salir

    <ion-icon name="log-out" class="iconos_navBar"></ion-icon>Salir

    <?php
    include 'Templates/cuerpo.php';
    include 'Templates/pie.php';

 ?>


text:
Q: XMLHttpRequest not working in Google Chrome Packaged Web App I'm writing a packaged Chrome Web App and trying to parse external XML.  It works when I download the XML file to my server, but does not work when I change the XML file to the location on the web.
For example, I am trying to access this file:  http://www.w3schools.com/xml/note.xml
Here is my JavaScript code (note that  HTML   ):
function dashboardContent() {
html="";

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.w3schools.com/xml/note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

html+=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
html+=xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
html+=xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;

document.getElementById("contentArea").innerHTML=html;

}

In my Chrome Web App manifest.json file, I put the following under permissions per Google's manifest requirement for Cross-origin XMLHttpRequests:
{
    "name": "BirdTrax",
    "version": "0.1.1",

    "description": "Birding explorer to help you plan birding trips and find recently eBirded sightings, rarities, and checklists in your area",
    "icons": {
         "16": "icons/helloWorld_16.png",
        "128": "icons/helloWorld_128.png"
    },

    "app": {
        "launch": {
            "local_path": "main.html",
            "container": "tab"
        }
    },

    "background_page": "background.html",
    "options_page": "options.html",

"permissions": [
  "http://www.w3schools.com/*",
  "notifications",
  "unlimitedStorage"
],

    "incognito": "split"

}

I'm not sure if I'm still missing something, but the code isn't working for me.  Any suggestions, tips, ideas?  I really appreciate any help!!

A: Suffice a wildcard after /. Otherwise, you're allowing your extension to only request pages at the root.
"permissions": [
  "http://www.w3schools.com/*",

In your case, you're requesting only one URL. It might be even better to restrict the pattern even more:
"permissions": [
  "http://www.w3schools.com/xml/note.xml",


text:
Q: Get a string from a Javascript Array using EVAL statement in iMacros I am trying to create a string array in Imacros, and then get a string value and store in var 2, so that i can use a different (random value) each time.
but when i write this, I have the error on second line:
SET !VAR1 EVAL("var config = ['myConfigParameter1', '500', '4.1234213', 'http://an.url/'];config.join(';')")
SET !VAR2 EVAL("var config = '{{!VAR2}}'.split(';');config[0]")

Iam trying to run it in Imacros firefox and on running this it gives error on second line stating:
s is undefined, line: 7 (Error code: -1001)
I followed this tutorial to get a string value from array in imacros.
http://www.iteamwork.de/imacros-scripting-use-more-than-x-variables-in-macro-script.html
What is wrong with that line?
How can i retrieve a random string and store in var2 so that i can use it in my imacros code ?
I also tried doing it core JS way by creating a separate js file but that didnt work either.
UPDATE:
Here is the full code:
VERSION BUILD=9030808 RECORDER=FX
SET !VAR1 EVAL("var config = ['myConfigParameter1', '500', '4.1234213', 'http://an.url/'];config.join(';')")
SET !VAR2 EVAL("var config = '{{!VAR2}}'.split(';');config[0]")
TAB T=1
wait seconds = 7
'TAG POS=1 TYPE=TEXTAREA ATTR=ID:chatmsg CONTENT=TestMessge
TAG POS=1 TYPE=TEXTAREA ATTR=ID:chatmsg CONTENT={{!VAR2}}
TAG POS=1 TYPE=INPUT:BUTTON ATTR=ID:sendbtn
wait seconds = 2
ONDIALOG POS=1 BUTTON=OK CONTENT=
wait seconds = 1
TAG POS=1 TYPE=INPUT:BUTTON ATTR=ID:disconnectbtn
ONDIALOG POS=1 BUTTON=OK CONTENT=
wait seconds = 2
ONDIALOG POS=1 BUTTON=OK CONTENT=
wait seconds = 1
TAG POS=1 TYPE=INPUT:BUTTON ATTR=*
ONDIALOG POS=1 BUTTON=OK CONTENT=

And here is my random line:
SET randomNumber EVAL("var min = 0; var max = 4; var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; randomNumber;")
SET !VAR2 EVAL("var config = '{{!VAR1}}'.split(';');config[{{randomNumber }]")

Random number is working fine but i dont know how to use the randomnumb variable inside the array to get random string. problem is in 2nd line now.

A: SET !VAR2 EVAL("var config = '{{!VAR2}}'.split(';');config[0]")

I think you meant for this to join the array var you just set, right? So it would be:
SET !VAR2 EVAL("var config = '{{!VAR1}}'.split(';');config[0]")


text:
Q: How to specify generic type as a generic (higher kinded types) In Typescript, is it possible to specify a generic type as generic? Specifically, I would like to be able to define a function signature as follows:
function events<T>(): T<Event>

However I am receiving the following error from the typescript compiler:
[ts] Type 'T' is not generic.

A: "generic type as a generic": if I understand correctly what you are trying to achieve is to use higher kinded types.
This not (yet) possible in Typescript: see this

A: Change the definition as below:
function events<T>(): Event<T>

Read more about the syntax here: https://www.typescriptlang.org/docs/handbook/generics.html


text:
Q: Strange behaviour with openssl subject-alternative-name extension I'm trying to use openssl to generate a certification with multiple alternative name.
I have my CA and its certification and its key.
Now, I have generate a ceritificate request with some subject-alternative-name and with command  openssl req -text -noout -in domain.csr  I've seen that is right with the extension subject-alternative-name in attributes.
In openssl.cnf I have set copy_extensions = copy.
The problem is that when I generate the certification I get the certification but there isn't  extension subject-alternative-name in attributes.
What kind of problem it can be?

A: I the openssl config, you need to have the SAN section, and you need to keep it until you issue it for yourself.
On my page you can find my generator tool for SSLs requests. Maybe this will help you.
http://vargaviktor.hu/openssl_generator_en.html


text:
Q: SQL CONTAINS doesn't work Hy, i'm try to execute this code
public function CardsTextSearch($text){

    $hashed_text = md5($text);
    echo "HASHED ".$text." IN ".$hashed_text."
";
    $result = array();
    $sql = "SELECT cardID,cardName FROM Cards WHERE CONTAINS(hashedCardName, '$hashed_text')";

    if ($sth = $this->DBH->query($sql) ){
        //echo "PREPARED
";
        //$sth->execute(array($hashed_text));
        echo "EXECUTED: ";
        var_dump($sth);
        echo "
";
        $row = $sth->fetchAll(PDO::FETCH_ASSOC);
        var_dump($row);
        echo "
ROW: ".$row."
";

    }else{
        echo "ERRORE
";
        print_r($this->DBH->errorInfo());
    }
    var_dump($result);
    echo "RESULT
";
    return $result;

}

Leaving aside the because of a search on the encrypted string (simply because the field  cardName is varchar (150), so do not indexable), can you tell me if there is any error in the code, because the query does not work, and the output is generated is the following:

HASHED Bad Moon IN 9e326d217f275a19ba1df92cb64be771
EXECUTED: Object(PDOStatement)#5 (1) { ["queryString"]=> string(100) "SELECT cardID,cardName FROM Cards WHERE CONTAINS(hashedCardName, '9e326d217f275a19ba1df92cb64be771')" }
  array(0) { }
  ROW: Array

I'm sure that there's an existing value of hashedCardName='9e326d217f275a19ba1df92cb64be771' in the DB, less sure that the column hashedCardName has been indexed.
It may be that the column has not been indexed or have I done something wrong in the code?
P.S.
I also try with $stmt = $this->DBH-> prepare() and execute() as u can see in some comment that i had left.

A: Contains doesn't work. Try Like or Instr:
SELECT * FROM Cards
WHERE hashCardName like '$hashed_text';

SELECT * FROM Cards
WHERE INSTR(hashCardName, '$hashed_text');

SqlFiddle here


text:
Q: Django admin crashes after Save and Continue redirects to None instead of id of the primary key. Help? I installed Django for the first time yesterday and trying it out in earnest today. I'm only planning to use it for the beautiful admin interface, Zend Framework for the rest.
I imported an existing table event into the admin. There's no join needed. But the primary key is not 'id' it's called "event" (following this naming convention). I obviously don't want this column's id# to appear in the data entry form.
Everything works fine, EXCEPT when adding a new event, I click Save and Continue Editing, it adds the event, but redirects the URL to
http://127.0.0.1:8000/admin/events/event/None/
and spits out this error
ValueError at /admin/events/event/None/

invalid literal for int() with base 10: 'None'

This is my models.py:
from django.db import models

class Event(models.Model):
    event = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=150)
    address_1 = models.CharField(max_length=150)
    url = models.URLField(max_length=500,verify_exists=False)
    start_date = models.DateField()
    end_date = models.DateField()
    ACTIVE_CHOICES = (
        (0, 'InActive'),
        (1, 'Active'),
    )
    active = models.CharField(max_length=1, default=1, choices=ACTIVE_CHOICES)
    def __unicode__(self):
        return self.title
    class Meta:
        db_table = u'event'

Any ideas what I'm doing wrong or how to fix this?

A: You probably want the PK to be an AutoField instead of an IntegerField so Django will automatically fill it in for you.  Otherwise you have to do it yourself in the save method or the admin interface:
class Event(models.Model):
    event = models.AutoField(primary_key=True)

A: This isn't a fix, but hopefully it can help shed light on this situation.
Behind the scenes when you hit "Save and Continue" what's happening is there are 2 URLs that are accessed...
/admin/events/event/add/
/admin/events/event/{id of newly created element}/

If you look at the error your getting, the URL that is' choking on is '/admin/events/event/None/'.  Note how where the id should be there is the value of 'None'?  It means that when a new record is created it probably isn't having a value set for 'event' (the pk).
If you were to check your SQL database you'd probably see the event column was null.
Steve Losh just posted the code (as I was typing) on how to solve this so I'll end my answer here.


text:
Q: Why kotlin.math functions does not have implementation of Long I have been working with kotlin for little over 2 years now.
Looking over what I learned in these 2 years, I  noticed that I have been using(num.toDouble()).toLong() for kotlin.math functions a bit too much. For example, Math.sqrt(num.toDouble()).toLong(). Two of my projects have extension function sumByLong() inside util created by team, because kotlin libs only have sumBy:Int and sumByDouble:Double and a lot of work in the project, uses Long.
In short, Mathematical operations using Long is more common than using Double or Float, yet Long has a very small footprint in kotlin standard library. And since kotlin.math is different than java.lang.Math, mixed usage is not a recommended practice.
Going over docs of kotlin.math, all functions except for abs, min, max, only have implementation for Float and Double only.
Can someone Explain like I am 5 the possible reasoning behind this. Something real, not silly stuff like devs were lazy, or more code means more work, which is all I could find in search engine results.
--
Update: Some Clarification
1. I can understand that in most cases, return types will contain floating point numbers. I am also talking about parameters lacking long counterpart. Maybe using Math.sqrt wasn't the best example, something like math.log, math.cos, etc would be better example, where floating return type us expected, but parameters doesn't even support Int
2. When I said "Long is more common than using Double", I was not talking about public at large, but was looking over my past two years working with kotlin. I am sorry if my phrasing wasn't clear.

A: Disclaimer: this answer may be a little opinionated, but I believe it is according to general consensus and best practices of using maths in computer science.
Mathematics for integers and for real numbers (floats) are really two much different math "sub-worlds". They're pretty separate, they have different uses and we usually don't mix them.
If we work on some physics, we do real-world simulations, we operate on units like temperature or speed, we use doubles. If we have identifiers (bank account number), we count something (number of bank accounts) or we operate on a discrete values with 100% precision (bank account value) we always use integers and never doubles.
Operations like sinus, square root or logarithm make perfect sense for physics, but not really for bank account values. They very often produce either very small or very large numbers that can't be safely represented as integers. They operate on approximations and don't really provide 100% precise results. They are continuous by nature while integers are discrete.
What is the point of using integers with sqrt() or log() if they almost always return a floating point result? What is the point of passing an integer to sin() if e.g. there are only 2 distinct angles smaller than square angle that can be represented as an integer: 0 and 1? Using integers with these functions is unnatural and impractical.
I can't think of a case where we have to often convert between longs and doubles. Usually, we operate either on longs or on doubles top to bottom and we don't convert between them too often. By converting we lose advantages of these specific "math sub-worlds", we sum their disadvantages. Maybe you should just keep using doubles in your application and don't convert to/from longs? Why do you use longs?
BTW, you mentioned that you can't/shouldn't use java.lang.Math in the Kotlin application. Well, if you look into java.lang.Math you will notice that... it supports only doubles :-)

A: In the case of ceil, it returns a Double because a Double has a bigger range of values than Long. Consider, for example:
ceil(Long.MAX_VALUE.toDouble() * 1000)

What would you expect it to return if it returned a Long? For further discussion, see Why does Math.ceil return a double?
In the case of log and trigonometric functions, the use cases requiring Long parameters are rare and the requirements varied. For example, should it round up, down, or to the nearest integral value? These are decisions that should be made for your particular project, and therefore can't be made in the stdlib.
In your project, you can simply define your required functions in a single, small source file, making your project's choice of rounding method, and then use it everywhere instead of converting at each call site, e.g.:
fun cos(n: Long): Long = cos(x.toDouble()).roundToLong()


text:
Q: Jenkins BlueOcean unable to connecto to GIT repo URL I have implemented a sample CI/CD pipeline using Jenkins for an application.
The GIT URL for the private repository specified in code checkout job works fine.
But when I use the same GIT Repo url to create a pipeline using "Blue Ocean" plugin it is throwing the following error:
Repository URL - Please enter a valid URL.
Can anyone please help what can be the possible error as I am unable to figure out as the normal job in the pipeline is working fine.

A: Instead of using http or https use ssh while providing the url, please see below or follow this:-
ssh://user@server:/GitRepo/project.git


text:
Q: Sending metadata using gRPC's context vs SendMsg/RecvMsg methods I really don't get what's the benefit of sending metadata through gRPC's context, which can only handle strings (binary data is base64 'd), while it is possible to use SendMsg() to send a well-known and defined protobuf type, and get rid of string-based serialization.
Why using the context is the only documented way of exchanging metadata?

A: By metadata we mean information that is added to http headers and in turn looked at by the server at the beginning of an RPC. This information could've been auth related information or some other metadata that an interceptor or service handler might want to look at to do some pre-processing before data exchange begins. Hope this is helpful.


text:
Q: how do I hide schema and migration information while running migration in adonisjs test I am new to adonis JS. I have looked at the docs and other resources but couldn't figure out how to only show the test results without all the migration up and down information.
As you can see from image below, the result of test is sandwich between migration up and migration down information which I don't need.
Silent argument is passd to vowfile.js as well. This removes the list of migration files run. But doesn't hide other unnecessary information.
const ace = require('@adonisjs/ace')
await ace.call('migration:run', {}, { silent: true })
await ace.call('migration:reset', {}, { silent: true })


text:
Q: How to send integer array as a parameter from endpoint without querystring from url in asp.net core webapi I have an endpoint that has a parameter that type of integer array.I want send some value from body as a json string.When I tried it , I was getting null value from parameter so I tried to send integer array from url but happen problem about of url length so I want to know that is possible to send it from request body or how to fix url length problem for 5.000 item
request body that I tried
{
  "Ids": [349]
}

endpoint function
[HttpGet]
public void GetModels([FromBody]List<int> Ids)
{
}

A: First, in general including a body in a GET request is often not considered very RESTful.  It is no longer specifically "banned" by RFC, but it is not typical.  That said, you can make this work in ASP.Net Core using the [FromBody] attribute.
The issue has to do with how you are formatting your JSON body. Using the signature for GetModels that you have listed above, the JSON body doesn't match the parameters.  Your JSON represents a top-level object with a property Ids that is an array of int, not just an array of it (or List).
If you want to use public void GetModels([FromBody]List<int> Ids) then your JSON body should simply be an array (e.g. [349,350,351]) and nothing else (no brackets, no "Ids" property name).
If you want to use the JSON body you list above, then you need another class to use for model binding, a DTO.  That DTO would look something like:
public class IdDto
{
   public List<int> Ids { get; set; }
}

and then your GetModels method would look like:

    [HttpGet]
    public void GetModels([FromBody] IdDto idDto)
    {
       var myIds = idDto.Ids;
    }

Lastly, be sure that your GET request has a Content-Type set to application/json or ASP.Net will return a 415 "Unsupported Media Type".


text:
Q: c# class being overridden and can not be assigned I am having a code like this
[System.Serializable] public class class1 {
    [System.Serializable] public class class2 {
        public int var1, var2; public string var3;
        public class2 () {}
        public class2 (int v1, int v2, string v3) {
            var1 = v1;
            var2 = v2;
            var3 = v3;
        }
    }
    public class2[] list;
}
public class1 _class1;
public void Assign () {
    _class1 = new class1 ();
    _class1.list = new class1.class2[3];
    for (int i = 0; i < 3; i ++) {
        _class1.list[i] = new class1.class2((int)Random.Range (10,20), (int)Random.Range (100,200), ((int) Random.Range(50, 75)).ToString ());
    }

}

this code i also connected with other scripts, which reads from here the values, but what i get is that
_class1.list[] all the objects inside this are frozen, i cannot change their value, i change thevalue and they got setted up again 0.
i use a code like this to copy
//inside class1
public static class1 copy (class1 tocopy) {
    class1 copy = new class1 ();
    copy.list = tocopy.list;
    return copy;
}
public class1 copy () {
    return class1.copy (this);
}

//inside class2
public static class2 copy (class2 tocopy) {
    class2 copy = new class2 ();
    copy.var1 = tocopy.var1;
    copy.var2 = tocopy.var2;
    copy.var3 = tocopy.var3;
    return copy;
}
public class2 copy () {
    return class2.copy (this);
}

even doing this, i get a class which is linked with that classX copy = new classX ();
and when i try to assign the value to this, it instantly reassigns the value it had when generated a copy.
i am doing this because when i was not using copy () it was making all the values of the list with the same last value, i was going to change the value of 1, and it was applied on all, they had a instance, a clone, i don't know how to call, a reference.
I don't know how to delete this reference that now i am referencing a new object, so now i have not reference with that class, so its better, it does not assign the values to the class which i copied. but i get the problem that i can't assign this.
How can i fix this?

A: The questions is not very clear but I think that the problem is because you are making just a shallow copy, try changing class1.copy to copy every item of list:
public static class1 copy (class1 tocopy) {
    class1 copy = new class1 ();
    copy.list = new class1.class2[tocopy.list.Length];
    for(int i = 0; i < tocopy.list.Length; i++) {
        copy.list[i] = tocopy.list[i].copy();
    }
    return copy;
}


text:
Q: nodejs es6 way of running task every second for 10 seconds I am trying to come up with an elegant implementation for an async function that attempts a check operation check() every t seconds for a maximum n number of times; i.e. I would like to immediately return if check() === true, otherwise I would like to bail out after t * n seconds (n attempts).
I have a working implementation using counter-based for-loop and simple delay:
// doc and pair are defined already
let delay = ms => new Promise(res => setTimeout(res, ms))
for (i = 0; i < 10; i++) {
  if (doc.key) {
    break
  }
  await delay(1000)
  doc = await DbModel.findOne(pair)
}

Is there a better way of achieving this using native es6 features (e.g. perhaps promisified versions of setTimeout and setInterval)?

A: You can give a try to node-scheduer. Very much similar to the cronjob. But the application must be kept on running.
It executes an event on a given interval. Make sure the job is executed after the desired interval every time and Put the repeated functionality there.


text:
Q: Logic Apps liquid template ask I am a complete newcomer to Liquid, started playing with it a few hours ago.
i am trying to parse a JSON and extract certain key value pairs out of it, yet i am not successful at all. the JSON is outputed from Azure Form Recognizer, and i am trying to do a Liquid json 2 json in Logic Apps.
the JSON looks like this
{
  "status": "success",
  "pages": [
    {
      "number": 1,
      "keyValuePairs": [
        {
          "key": [
            {
              "text": "Page No:",
              "boundingBox": [
                507.4
               ]
            }
          ],
          "value": [
            {
              "text": "1",
              "boundingBox": [
                586.8
              ],
              "confidence": 1.0
            }
          ]
        },
....
...

what i am looking for is to loop through the keyValuePairs array, and then pull the "text" element from the "key" array, and the "text"+"confidence" element from the "value"array.
Could you please help me in understanding the approach here? I tried something like this, but the array comes back empty
{
"results":[
{% for kvp in content.keyValuePairs  %}

{% for mykey in kvp.key  %}

"thiskey":"{{mykey.text}}
{%- endfor -%}
{% for myval in kvp.value  %}

"thisvalue":{{myval.text}}
"thisconfidence":{{myval.confidence}}
{%- endfor -%}
{%- endfor -%}
]
}

And second question: what's the best approach for debugging Liquid, so i can see where i am getting it wrong and adjust?
Thank you!

A: According to the sample of json data and the liquid template you provided, I know there are more than one object under the property keyValuePairs in your json data. So I think using "Parse JSON" action is not a good solution for it, we'd better use liquid template as you mentioned in your question. But I'm confused about that if there are more than one object under the property pages in your json data ?
Now I assume the json data just has one object under the property pages and provide the solution of liquid template for your reference (If the json data has more than one object under the property pages, please provide some more details of your requirements and I will modify my solution).
I assume your json data like below:
{
    "status": "success",
    "pages": [
        {
            "number": 1,
            "keyValuePairs": [
                {
                    "key": [
                        {
                            "text": "Page No:",
                            "boundingBox": [
                                507.4
                            ]
                        }
                    ],
                    "value": [
                        {
                            "text": "1",
                            "boundingBox": [
                                586.8
                            ],
                            "confidence": 1.0
                        }
                    ]
                },
                {
                    "key": [
                        {
                            "text": "Page No:",
                            "boundingBox": [
                                507.4
                            ]
                        }
                    ],
                    "value": [
                        {
                            "text": "2",
                            "boundingBox": [
                                586.8
                            ],
                            "confidence": 2.0
                        }
                    ]
                }
            ]
        }
    ]
}

1. We need to get the object under the property pages and put it in the "content" of "Transform JSON to JSON" action. We can parse the whole json data(with "Parse JSON" action) first and do something like below:

2. Upload the liquid template to integration account, please refer to my liquid template:
{
    "results":[
        {% for kvp in content.keyValuePairs  %}
            {%- if forloop.Last == true -%}
                {
                    {% for mykey in kvp.key  %}
                        "thiskey": "{{mykey.text}}",
                    {%- endfor -%}
                    {% for myval in kvp.value  %}
                        "thisvalue": "{{myval.text}}",
                        "thisconfidence": "{{myval.confidence}}"
                    {%- endfor -%}
                }
            {%- else -%}
                {
                    {% for mykey in kvp.key  %}
                        "thiskey": "{{mykey.text}}",
                    {%- endfor -%}
                    {% for myval in kvp.value  %}
                        "thisvalue": "{{myval.text}}",
                        "thisconfidence": "{{myval.confidence}}"
                    {%- endfor -%}
                },
            {%- endif -%}
        {%- endfor -%}
    ]
}

3. After running this logic, we can get the result as:
{
  "results": [
    {
      "thiskey": "Page No:",
      "thisvalue": "1",
      "thisconfidence": "1"
    },
    {
      "thiskey": "Page No:",
      "thisvalue": "2",
      "thisconfidence": "2"
    }
  ]
}

Something you need to be aware of:

*

*Since we put the object under the property pages to the content of "Transform JSON to JSON" action, so the content in the liquid template represents it.

*In liquid template, we need to be careful about the comma character, so I use {%- if forloop.Last == true -%} to judge if it is the last object in the loop, and then judge if we need to add the comma character.
For your second question about what's the best approach for debugging Liquid ?, unfortunately I think we can just complete the liquid template and upload to the integration account, then we can see the result. I don't know if there is a way for us to debug it easily.
Hope it helps~

A: I have tried to design workflow using your sample JSON payload.
I have parsed the JSON schema and extracted the required values from it.
Since your JSON payload is a bit complex, we need to use Logic App Expressions to extract the value out of it.
Payload I used:
{
"status": "success",
"pages": [{
    "number": 1,
    "keyValuePairs": [{
            "key": [{
                "text": "Page No:",
                "boundingBox": [
                    507.4
                ]
            }],
            "value": [{
                "text": "1",
                "boundingBox": [
                    586.8
                ],
                "confidence": 1.0
            }]
        },
        "null"
    ]
}]

}
Once you get the JSON output from the upstream actions, you have to parse it.

Now, Initialize a couple of variables to get the required value from the parsed JSON.
Expression to be used in the first variable: concat(body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['key'][0]?['text'],body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['value'][0]?['text'])
Expression to be used in the second variable: body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['value'][0]?['confidence']

Finally, the logic apps after your Form Recognizor will look something like this:

I hope it helps!


text:
Q: Multiple async/await chaining How to make multiple async/await chaining in C#?
For example, start few HTTP requests and then do not wait all of them, but start new request after each completed?

A: If you want to perform some async action on a collection of items with a limited degree of parallelism, then probably the simplest way is to use ActionBlock from TPL Dataflow, since it supports async delegates (unlike most other parallel constructs in TPL, like Parallel.ForEach()).
var block = new ActionBlock<string>(
    url => DownloadAsync(url),
    new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = few });

foreach (var url in urls)
    block.Post(url);

block.Complete();
await block.Completion;

A: The easiest way to do this is to write an async method:
async Task DownloadAndFollowupAsync(...)
{
  await DownloadAsync();
  await FollowupAsync();
}

Which you can then use with await Task.WhenAll:
await Task.WhenAll(DownloadAndFollowupAsync(...),
    DownloadAndFollowupAsync(...));

A: You can use the ContinueWith extension method of Tasks for this purpose or the extension that takes a Func and is used to return results.


text:
Q: What is the advantage of GZIP vs DEFLATE compression? I have a web site in asp.NET 4 (C#).
I'm trying to find a way to better optimize bandwidth for my website.
I read many articles saying that DEFLATE is faster and smaller that GZIP because GZIP (based on DEFLATE) adds some extra data.
Checking the headers of bing.com and google.com it seems that they both send GZIP-encoded data.
Assuming what I read is true, I miss the advantage of GZIP in this case. So I suspect there should be a good reason to prefer GZIP to DEFLATE.
My questions:

*

*Does GZIP offer any advantage over DEFLATE I'm not aware of?

*Any clue why major search engines use GZIP?

Here's the code I'm using to send DEFLATE (from Global.asax):
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {

        HttpApplication app = sender as HttpApplication;
        string acceptEncoding = app.Request.Headers["Accept-Encoding"];
        Stream prevUncompressedStream = app.Response.Filter;

        if (!(app.Context.CurrentHandler is Page ||
            app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
            app.Request["HTTP_X_MICROSOFTAJAX"] != null)
            return;

        if (acceptEncoding == null || acceptEncoding.Length == 0)
            return;

        acceptEncoding = acceptEncoding.ToLower();

        if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
        {
            // defalte
            app.Response.Filter = new DeflateStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "deflate");
        }
        else if (acceptEncoding.Contains("gzip"))
        {
            // gzip
            app.Response.Filter = new GZipStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "gzip");
        }
    }

A: Gzip is the more reliable because it is deflate plus a few headers and a check sum. In other words gzip is deflate, and extra headers and check sum. Deflate is checked with adler32, which is also part of gzip. Because the gzip payload is a DEFLATE-compressed payload.
Deflate info
Gzip info

a gzip file/stream contains:
- a 10-byte header, containing a magic number, a version number and a time stamp
- optional extra headers, such as the original file name,
- a body, containing a DEFLATE-compressed payload
- an 8-byte footer, containing a CRC-32 checksum and the length of the original uncompressed data

A: The other answer is mostly wrong. The "deflate" value for the Content-Encoding HTTP header is a misnomer that actually means ZLIB. Given that, both have checksums and the same compressed content. They only differ in their headers/footer and which checksum they use.

gzip
"deflate" (zlib)

Header size
10 bytes
2 bytes

Footer size
4 bytes
0

Checksum
CRC32
Adler-32

Compression algorithm
DEFLATE
DEFLATE

Specification
RFC1952
RFC1950

Historically, "deflate" was problematic because early Microsoft IIS servers would send raw deflate data instead of zlib data (see https://stackoverflow.com/a/9186091/1218408). To work around that, it became common to just use gzip.
Deflate is very slightly faster because Adler-32 is typically faster to compute than CRC32, but the majority of the time is spent actually compressing data and not calculating the checksum.


text:
Q: Cannot run program "python3" I tried to installed SPARK in my windows 10 (64) and set environment variables for: SPARK_HOME, HADOOP_HOME and JAVA_HOME, yet, when I try to run a python programlike this:
    *'''spark-submit SparkRuming.py'''*

I tried to change my environment variables to may possible places, but I'm still getting this:

    *'''Exception in thread "main" java.io.IOException: Cannot run program "python3": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at org.apache.spark.deploy.PythonRunner$.main(PythonRunner.scala:97)
        at org.apache.spark.deploy.PythonRunner.main(PythonRunner.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
        at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:951)
        at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
        at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
        at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
        at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1030)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1039)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(ProcessImpl.java:444)
        at java.lang.ProcessImpl.start(ProcessImpl.java:140)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 14 more'''*

I'm sure I'm missing some environment variables or I'm pointing at the wrong place, does anybody have the same issue?


text:
Q: Bitmap copy in camera folder I'm having an odd problem on saving my bitmap image that I got from a LayoutView. The code below creates the bitmap and should export as an image to the palettes folder on the SD card. It actually does that, but there is also a duplicate copy of the bitmap in my Camera folder when I open up the Gallery app. Is there a way I can just copy into the folder alone without having a duplicate in the Camera folder? Also if there was a way you can delete the same copy in the Camera folder, that would work too. Thanks!
LinearLayout paletteView = (LinearLayout)findViewById(R.id.ExportBitmapLayout);
paletteView.setDrawingCacheEnabled(true);
paletteView.buildDrawingCache();
Bitmap bm = paletteView.getDrawingCache();

String filename = "PALETTETITLE";
filename.toLowerCase();
filename.replace(" ","_");
filename = filename.substring(0, (filename.length() < 30) ? filename.length() : 29);

ContentValues values = new ContentValues();
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.TITLE, filename);

boolean created = createDirIfNotExists("palettes");

if (created)
    Log.i("Directory created","OK");
else
    Log.i("Directory exists","OK");

//if successful
try
{
    OutputStream fOut = null;

    String longString = Environment.getExternalStorageDirectory()
            + File.separator + "palettes" +File.separator + filename+".jpg";

    File f = new File(longString);
    fOut = new FileOutputStream(f);

    bm.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

    fOut.flush();
    fOut.close();

    MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), filename, filename);

    Context context = ExportMenuImageActivity.this.getApplicationContext();
    Toast toast = Toast.makeText(context, "Image saved to Gallery! NOTE: Unintentional save in Camera folder. Fix in next update.", Toast.LENGTH_LONG);
    toast.show();

    MediaScannerConnection.scanFile(context, new String[] {longString}, null, new MediaScannerConnection.OnScanCompletedListener()
    {
        public void onScanCompleted(String path, Uri uri)
        {
        }
    });

}

catch (FileNotFoundException e)
{
    e.printStackTrace();
}

catch (IOException e)
{
    e.printStackTrace();
}

A: Here is the complete solution of your problem.You can not do anything like protecting the camera folder to save images. But you can delete the latest image jsut after your image inserted inside the database.

Here is the code for deleting the latest file from the camera folder, Just do copy and paste it and call this method whenever you want to delete the latest file from you camera folder..

private void deleteLatest() {
        // TODO Auto-generated method stub
        File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );

        //Log.i("Log", "file name in delete folder :  "+f.toString());
        File [] files = f.listFiles();

        //Log.i("Log", "List of files is: " +files.toString());
        Arrays.sort( files, new Comparator<Object>()
                {
            public int compare(Object o1, Object o2) {

                if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                    //         Log.i("Log", "Going -1");
                    return -1;
                } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                    //     Log.i("Log", "Going +1");
                    return 1;
                } else {
                    //     Log.i("Log", "Going 0");
                    return 0;
                }
            }

                });

        //Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
        files[0].delete();

    }

If still you have any query then let me know!!!
Cheers...


text:
Q: How to save frequently used data in android? This question might seem too common, and I've checked many posts in SO, and other sites too but I didn't get any proper answer to what I'm actually searching
What is the best possible way to save frequently used data?
Here "frequently used data" means all those data which are not worth saving in a database or shared preferences,nor is it suggestible to fetch every time, for example the height and width of the device, the database path,database name
I usually save all these data in a separate class where all the variables are generally static.
I fetch this data when the app starts or in the base activity, and use it wherever its necessary, may be in the activity,or in the adapter, or any parser class, etc..
Everyone knows that static data gets cleared when the phone requires more memory, but even if I save all the data in shared preference too, i can't get a context for the shared preference, or database each and every time i need the data. And these variables must be accessed from any class.
In my app, I name this class as AppConstant, and all my data is saved in static variables within this class, but all the data gets wiped out if I open 5-6 other apps.
So when I open my app again the view is again created in onCreate(), right now I'm checking within the activity, if my required data in the AppConstant is cleared or not, if cleared I'm fetching it from shared preferences.
But I'm hoping for a better alternative. Is there any?
Please help me out.
Thanks

A: First, the OS does not "clear" static data when memory is low.  This is what it appears to do, but it is not. If you use a singleton class for example, it will remain intact. What is happening is that the OS is killing your application to free up memory. Upon restart (assuming it happens within about 30 minutes), the OS will restore the state as it was before it was killed. Essentially it restarts the activity that was visible when your app went into the background.  As you know, activities can be killed and easily restarted (happens, for example, when you rotate your device).
However, if you create your singleton in the first activity of your app, it will NOT be present when the OS restarts your app as above - so it appears that the OS has "cleared" the data in your singleton.
Your solution of checking if the static data is there in onCreate() will work and I believe it is the only solution.


text:
Q: This simple Python Fraction Adder is not fully robust and is recieving errors. How can it be improved? I have written a fraction adder in Python for my computer science class. However, I am running into problems with the final answer reduction procedure.
The procedure uses the "not equal" comparison operator != at the start of a for loop to test whether, when dividing the numerator and denominator, there will be a remainder. If there will be a remainder (numerator % denominator ≠ 0), the procedure executes: each gets divided by n, then n increments and the for loop runs again. This continues until they divide evenly into each other.
Firstly, I am recieving a syntax error:
python FractionAdder.py 2 4 6 8
File "FractionAdder.py", line 23
for ansnum % n != 0 and ansdenom % n != 0:
                ^
SyntaxError: invalid syntax

Secondly, the for loop is not fully robust. My intended purpose was to have it reduce the final answer to its simplest form, but right now, it is only continuing to increment n and reduce until the numerator and denominator divide into each other evenly. This is a problem: 3 divides evenly into 6, but 3/6 is not in its simplest form. May I have some suggestions as to how to improve the robustness of my procedure, such that n continues to increment and the loop keeps cycling until the simplest form has been achieved? (Is there a better way to structure my conditional to achieve this?)
Full Code:
import sys
num1 = int(sys.argv[1])
denom1 = int(sys.argv[2])
num2 = int(sys.argv[3])
denom2 = int(sys.argv[4])

n = 1

# Find common denominators and adjust both fractions accordingly.
while denom1 != denom2:
    denom1 = denom1 * denom2
    num1 = num1 * denom2

    denom2 = denom2 * denom1
    num2 = num2 * denom2

# Add the numerators and set the ansdenom (denom1 and denom2 should be equal by this point if LCD function worked)
ansnum = num1 + num2
ansdenom = denom1

# Reduce the answer.
n = 2
for ansnum % n != 0 and ansdenom % n != 0:
    ansnum = ansnum / n
    ansdenom = ansdenom / n
    n += 1

print("The sum of the two fractions is:" + str(ansnum) + "//" + str(ansdenom))

Thanks in advance!

A: The error you see is derived by the wrong usage of for where while is the right type of loop (for is for iteration, while for condition).
Nevertheless, your logic at deciding the common denominators is flawed, and leads to an infinite loop. Please read about least common multiple, and consider the following pseudocode for determining the "new" numerators:
lcm = lcm(den1, den2)
num1 *= lcm / den1
num2 *= lcm / den2

A: You are trying to write a greatest-common-denominator finder, and your terminating condition is wrong. Euclid's Algorithm repeatedly takes takes the modulo difference of the two numbers until the result is 0; then the next-to-last result is the GCD. The standard python implementation looks like
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

There is an implementation already in the standard library, math.gcd.
from math import gcd
import sys

def add_fractions(n1, d1, n2, d2):
    """
    Return the result of n1/d1 + n2/d2
    """
    num   = n1 * d2 + n2 * d1
    denom = d1 * d2
    div   = gcd(num, denom)
    return num // div, denom // div

if __name__ == "__main__":
    if len(sys.argv) != 5:
        print("Usage: {} num1 denom1 num2 denom2".format(sys.argv[0]))
    else:
        n1, d1, n2, d2 = [int(i) for i in sys.argv[1:]]
        num, denom = add_fractions(n1, d1, n2, d2)
        print("{}/{} + {}/{} = {}/{}".format(n1, d1, n2, d2, num, denom))


text:
Q: Ground Plane Tips for Beginners I have made a few PCB's over the past few months as I have started to learn about design. All of the circuit boards have been Arduino based, so nothing to powerful. I design them up in Eagle and I know this is bad, but I have just used the Auto-router for everything, including the ground and power lines.
My boards have worked fine with this (maybe except for one thing), but I know this is very bad practice. I have been doing some research on ground planes and from what I have read I have not found a reason not to use them on your 2 layer PCB. Should I always add a ground plane to the bottom of my circuit board? When I look at other example boards in Eagle like the Arudino Mega, I notice it does not have a ground plane and I would like to know why someone would not use one. Also, is it okay to run signal wires through your ground plane?
One other question I have is when is it okay to use the Auto-router. From what I found online it should be fine to auto-route signal wires, and that I should manually route ground and power traces. And that these traces should be much thicker than the signal traces.
My last question is about ground loops. I think I have paranoid myself about ground loops and think that they are always gonna happen. As long as I have everything attached to ground on my board (and I only have one common ground), then there should be no issue in having a ground loop correct?
Thank you for the help, I am still very much a beginner with all of this.

A: A ground plane should be used to provide a nice, solid, low impedance path to ground. Some people, and almost all hobbyists (generalising), use it as a lazy way to hook up the ground connection as obviously this is used in a lot of places. In an ideal world, this means no other traces through it, and direct connection to the relevant pins. You may (will) have to break these rules in a real 2-layer board, but you can get much closer on a 4 layer board.
In something like an Arduino clone, you can happily use a ground plane and it is likely to work fine. Likewise, you can split the plane with signals, especially if you have no sensitive analog components, on projects like this. It's good practice not to, of course, but don't get too hung up at this stage of learning.
Which leads to autorouter. As a (weakly held) general rule, don't use it! While it may find paths for you, it is likely that thinking more about your component placements and general layout will be far more beneficial as a beginner. The real power of the autorouter is actually for advanced users who have to route out 1000s of pins from tiny ICs. Typically, you lay out as much you can (be bothered) by hand - this will usually make you place components logically, rather than just spattered all over the board. For a design the size you are describing, don't use it. Personally, I route sensitive signals first (local decoupling, small signal analog, fast digital etc), then power/ground, then hook the remaining airwires.
On a single board, you will not have a ground loop. Unless for some reason you have two different power supplies feeding the board. Ground loops tend to be more of a problem in small signal analog, less so in digital designs and it's easier to isolate with digital protocols.

A: This is a hard question to answer fully.
Things that argue in favor of having a ground plane:

*

*high speed digital busses

*SDIO

*SDRAM

*DDR

*USB

*Ethernet

*RF signals

Things that don't really need a ground plane

*

*Analog Audio (but still needs attention to noise issues)

*SPI bus (marginal...)

*I2C bus

*I2S (digital audio)

*Low-speed ADC's (1MHz or less)

Personally, I always try to route my signals on a single layer and use the bottom as a ground plane for simple utility boards. Careful placement is critical to achieve this. If needed I will run a few traces on the ground plane, but I try to keep them as short as possible.
For production 2-layer boards that don't need a ground plane, I still try to fill all unused space with copper on top and bottom, and use GND vias to interconnect in lots of places. I try to avoid having large sections of copper on top that are not bonded to the bottom, and vice verse. I will move stuff around a bit to make sure I get good interconnection and continuity of GND.
For 4 layer boards, I always use a ground plane and try very hard to have zero tolerance for traces or any nets other than ground on that plane. Typically there is also a generic "power" plane. On that one I will allow power fills or power traces usually.
A lot of this is to make sure the board can pass radiated emissions testing. If you don't need to do that, you only have to worry that the board works. You can be a lot less stringent.
In the end, any design that meets all its requirements is good enough. It is not necessarily a problem to just use the autorouter, but be careful if your board has any of the things in my list that generally require a ground plane. Or maybe route those things first, then let the autorouter take over.

A: Decades ago I worked near a guy who cranked out the assembly-level device-drivers for a conveyor-belt distribution system. He also designed moderate-performance embedded-systems for where a PC_AT was overkill; in some cases, large amounts of Input/output pins were needed, and he happily cranked out custom I/O expanders, using a AutoRouter.
I once happened to examine the 2-layerPCB I/O Expander, which used TTL logic, and noticed the long-thin 1/16" GROUND trace that Daisy-Chained around the several dozen
TTL ICs. I asked him, and he replied "Has never been a problem."
However, about 4 years later (he having died in a plane crash) and I had moved from systems-and-PCBs to systems-and-silicon. My boss asked "xxxxx called from YYYY company. They wonder if we have any ideas as to why these embedded systems will randomly go into MCU_reset?"
I, without a pause, simply stated "The grounds he (the deceased) used are not planes, but long thin Daisy_Chains. Tell xxxxx to convert those PCBs to Ground_plane PCBs."
WHy was this ----- Daisy_Chain grounds a problem?
Here is the math. Assume TTL, assume noise immunity of at most 1 volt.
If we find inductive spikes or kicks in the Ground that reach even 1/2 volt, we have
found the problem.
What will we find?
Assume the Ground Trace runs 3 sweeps across the PCB, of 8" each, 24" total, or 4/5 meter and thus approximately 4/5 of microHenry, or 800 nanoHenries.
Assume the TTL logic power demands exhibit 10mA peaks that rise in 10 nanoSeconds.
Is this a problem?
V = L * dT/dT
V = 800nH * 10mA/10nS = 800 nH * 1mA/1nS = 800 * 0.001 nH/nS = 0.8 volts
Thus with just ONE (ONE) TTL gate causing Ground currents, the entire PCB is at risk.
TWO CHOICES:
(1) Use a Ground GRID (My first large TTL project, with 75 SSI TTL, never had sproblems; it used X and Y wires running past each of the ICs; thus each IC had at least two GND returns coming from wherever the TTL signal ended up. The GRID was made of 5 banks of 15 ICs; thus from left to right there were 5 parallel wires (#22 bus wire), of length about 15 inches or 30 inches round-trip in air or about 3 nanoSeconds electrical-length for a
Standard TTL speed of 10 or 15 nanosecond gate prop-delay (tho the IDD surges are what I am discussing here)
(2) use a Ground Plane; the premier prototyping technology at that time was WIREWRAP from Augat or Robinson_NUget. I could not afford those, so a ground-grid was my (successful) solution. By the way, each TTL IC had 0.1uF soldered between pin 7 and 14 (for those 14-pin DIPs), and all the VDD surges were well provided right at the IC.


text:
Q: Error uploading big extensions to joomla on a localhost I get the following error when I tried uploading the Akeeba Backup extension on my localhost: "There was an error uploading this file to the server."
I tried uploading JCE Editor and it worked fine. I understand this error appears because I cannot upload extensions bigger than X MB (JCE is 1,5MB and Akeeba is 2,25MB). So my guess is I cannot upload extensions bigger than 2MB.
Researching I came across two solutions, neither worked for me.
First solution:
In the file ini.php find the following line upload_max_filesize = xM and replace "x" with a value of 10 (for example). I could not find the above mentioned line in the ini.php file.
Second solution:
In your .htaccess add the following:
php_value max_upload_size 10M

added the code, nothing happened.
I am using Joomla 3.2

A: Rather than trying to manually find the correct line to edit, in your code editor, use Ctrl + F which will open up the "find" box. Copy and paste upload_max_filesize and click "find". This will take you to the exact line where it is located. Once changed, save the file and restart Apache/All services on your localhost.


text:
Q: Unmarshalling ethernet frames and data alignment So I'm trying to unmarshall ethernet frames eth and ip headers. I have a program skeleton that reads input data from file and serves me a struct with the frame data.
I have googled and read other posts on the topic but i'm getting nowhere. For example:
Data Alignment with network programming
http://en.wikipedia.org/wiki/Data_structure_alignment
I not sure what the problem is. Obviously im new to C.
If I just try using memcpy and copy data into my structs of eth and ip headers most of the data comes out nice, but not the ip adresses in my ip struct. I also tried reading from the input struct in 1byte, 2byte and 4byte chunks but it doesn't give me correct data.
Here is an example of input data frame from the input file:
200 0000 0002 0200 0000 0012 0800 4500 0026 17d4 81e7 ff01 0000 0a02 0002 0c0c 0c0c 0000 e802 c04b 0004 3e89 3325 0006 ddef 0809

Here is the header structs im using
struct ethhdr{
    char     da[6];
    char     sa[6];
    uint16_t pt;
};
typedef struct ethhdr ethhdr;

struct iphdr{
#ifdef WORDS_BIGENDIAN
    unsigned int ip_v:4;        /* version */
    unsigned int ip_hl:4;       /* header length */
#else
    unsigned int ip_hl:4;       /* header length */
    unsigned int ip_v:4;        /* version */
#endif
    uint8_t  ip_tos;            /* type of service */
    uint16_t ip_len;            /* total length */
    uint16_t ip_id;         /* identification */
    uint16_t ip_off;            /* fragment offset field */
    uint8_t  ip_ttl;            /* time to live */
    uint8_t  ip_p;          /* protocol */
    uint16_t ip_sum;            /* checksum */
    uint32_t ip_src, ip_dst;            /* source and dest address */
};
typedef struct iphdr iphdr;

The input data struct that im being served.
struct fe_context{
    char   *pkt;         /* Pointer to packet */
    size_t  len;         /* Length of packet */
    void   *if_in;       /* Incoming interface - handle */
};
typedef struct fe_context fe_context;

Sample code of how I've tied to read the data.
int fe_process(fe_context *c)
{
  printf("\n\nPacket received!\n");
  printf("memcpy to header structs:\n");
  ethhdr * ethh = (ethhdr *) malloc(sizeof(ethhdr));
  iphdr * iph = (iphdr *) malloc(sizeof(iphdr));
  memcpy(ethh, c->pkt, sizeof(ethhdr));
  memcpy(iph, c->pkt+sizeof(ethhdr), sizeof(ethhdr));

  printf("MAC SA: %02x:%02x:%02x:%02x:%02x:%02x\n", ethh->sa[0], ethh->sa[1], ethh->sa[2],
      ethh->sa[3], ethh->sa[4], ethh->sa[5]);
  printf("MAC P: %04x\n", ntohs(ethh->pt));

  printf("IP Ver: %x\n", ntohl(iph->ip_v));
  printf("IP IHL: %x\n", ntohl(iph->ip_hl));
  printf("IP TTL: %i\n", iph->ip_ttl);
  printf("IP Checksum: %x\n", ntohl(iph->ip_sum));
  printf("IP SRC: %08x\n", ntohl(iph->ip_src));
  printf("IP DST: %08x\n", ntohl(iph->ip_dst));

  char * cp = c->pkt;
  printf("\nPacket read by char:\n");
  char data;
  int p;
  for(p = 0; p < 52; p++) {
    data = *cp;
    cp++;
    printf("%02x", data);
    if(p%2==1) {
      printf(" ");
    }
  }
  printf("\n\n");
  cp = c->pkt;
  printf("Packet read by uint16_t:\n");
  uint16_t data16;
  for(p = 0; p < 52/2; p++) {
    data16 = *cp;
    cp+=2;
    printf("%04x ", ntohs(data16));
  }
  printf("\n\n");
  cp = c->pkt;
  printf("Packet read by uint32_t:\n");
  uint32_t data32;
  for(p = 0; p < 52/4; p++) {
    data32 = *cp;
    cp+=4;
    printf("%08x ", ntohl(data32));
  }
  printf("\n\n");

  return 0;
}

And here is its output with the above test data input.
Packet received!
memcpy to header structs:
MAC SA: 02:00:00:00:00:12
MAC P: 0800
IP Ver: 4000000
IP IHL: 5000000
IP TTL: 255
IP Checksum: 0
IP SRC: 0a020000
IP DST: 00000000 // It looks good up until here. this should be 0c0c0c0c

Packet read by char:
0200 0000 0002 0200 0000 0012 0800 4500 0026 17ffffffd4 ffffff81ffffffe7 ffffffff01 0000 0a02 0002 0c0c 0c0c 0000 ffffffe802 ffffffc04b 0004 3effffff89 3325 0006 ffffffddffffffef 0809

Packet read by uint16_t:
0200 0000 0000 0200 0000 0000 0800 4500 0000 1700 81ff ffff 0000 0a00 0000 0c00 0c00 0000 e8ff c0ff 0000 3e00 3300 0000 ddff 0800

Packet read by uint32_t:
02000000 00000000 00000000 08000000 00000000 81ffffff 00000000 00000000 0c000000 e8ffffff 00000000 33000000 ddffffff

As you can see the data in the structs is fine all the way until the DST IP. Could this be because of padding/data alignment? It would appear, by looking at the char read, that the problem somehow happens in the ip header part of the data? When I read by char, where does these 'f's come from?
I tried checking the c->pkt pointer adress and its even. I'm not even sure if that matters though? Im thinking that it will always be since malloc got that for me. Whats the right way of reading this data for for parsing/unmarshalling? I am going to be doing alterations to this data so I would prefer to get the data into neat structs.
Do I have a simple error in my code or am I going about it the wrong way? Any help is much appreciated!

A: I noticed you made an error on the line:
memcpy(iph, c->pkt+sizeof(ethhdr), sizeof(ethhdr));
You're copying sizeof(ethhdr) bytes for your IP header instead of sizeof(iphdr) which is what you want here. Seems like you made a typo.


text:
Q: Как удалить элемент многомерного массива по совподающим значениям из подмассивов? foreach($Goods as $index1 =>$massiv1)
{
  $current=$massiv1['Link'];
  do{
    next($Goods);
  }
  while($current!=$massiv1['Link']);//Делаем пока не равно
  if(($current)==($massiv1['Link']))
  {
    unset($Goods[$index1]);

  }

}

нужно, чтобы допустим если в одном подмассиве ссылка равна ссылке из другого то этот элемент  основного массива удаляется..
а тут все удаляется почему-то..
A: Конечно все и удаляется, ведь по действию в третьей строке:
$current=$massiv1['Link'];

Т.е. уже понятно что $current==$massiv1['Link'] вернет true и ниже стоящее условие будет всегда выполняться:
if(($current)==($massiv1['Link']))
{
unset($Goods[$index1]);

}

По всей видимости в третьей строке должна быть другая переменная.
A: Вы приравниваете $current=$massiv1['Link'];
А дальше сравниваете $current с $massiv1['Link'] (if(($current)==($massiv1['Link']))).
Потеряли переменную и ошибка в логике


text:
Q: Plot slice through 3-D xarray.Dataset I would like to plot a slice through a 3-D xarray.Dataset as illustrated below:

This is how I started off (for simplicity, using the tutorial air_temperature dataset)
# import packages
import xarray as xr
import numpy as np

# load dataset
ds = xr.tutorial.open_dataset("air_temperature")

# get slice values
tgt_lon = xr.DataArray(np.linspace(220, 280, num=15), dims="lon")
tgt_lat = xr.DataArray(np.linspace(30, 50, num=15), dims="lat")

# crop to region of interest - this works fine
da = ds.sel(lon=tgt_lon,
            lat=tgt_lat,
            method="nearest")

Now we still have a 3-D xarray.Dataset. For a 2-D plot, we want to stack longitude and latitude to a distance array relative to a zero point (here: corner x0/y0 as shown in figure).
# zero point: lat_min/lon_min
lon_orig = da.lon.min().values
lat_orig = da.lat.min().values

# stack longitude and latitude -- gives tuple for dist
sta = da.stack(dist=('lon', 'lat'))

... and then we could compute the distance relative to lon_orig/lat_orig by looping over sta. For the actual plotting (using contourf), we would then flatten the arrays to 1-D arrays. This all seems a bit tedious and I was wondering if I am missing the obvious way of doing this?
Ultimately, we want three 1-D arrays with the same shape for plotting:

*

*z (for this dataset: time)

*distance (relative to x0/y0, here computed from longitude and latitude)

*the actual data (here: air temperature)

Thanks!

A: Setting up my Example
First of all I am going to use a different example since I want to know what I am supposed to get as a result. My example is a 100x100x100 array containing a ball of radius 50.
I have adopted the code from this answer to plot it.
n = 100

def distance_from_center(x,y,z):
    V = np.stack([x-n/2,y-n/2,z-n/2])
    return np.linalg.norm(V, axis=0)

ball = np.fromfunction(distance_from_center, (n, n, n), dtype='float')
ball = (ball > 50).astype('int')

Elementary Solution
You can do such a thing in 4 lines of code. So I will do that first before I get more fancy. My first slice is from corner to corner. Like this:

I have marked where I will slice in green.
t = np.arange(n)
slice = ball[t,t,:]
plt.matshow(slice.T, cmap='gray')
plt.gca().set_aspect(1/2**(1/2))

Notice here that I have to set the aspect ratio to one over square root of two since the 50 pixels in the diagonal direction are a longer distance than the 50 in the ordinary direction. The picture looks like expected. There is white space on both sides since the corners of the array provide space for it but we still get a circle.
You can do other cuts like this but you're always thinking about how to get whole number coordinates.
More Sophisticated Solution
The alternative is to just take any coordinates and interpolate between points where you don't hit points perfectly.
import itertools

class Image_knn():
    def fit(self, image):
        self.image = image.astype('float')

    def predict(self, x, y, z):
        image = self.image
        weights_x = [(1-(x % 1)).reshape(-1), (x % 1).reshape(-1)]
        weights_y = [(1-(y % 1)).reshape(-1), (y % 1).reshape(-1)]
        weights_z = [(1-(z % 1)).reshape(-1), (z % 1).reshape(-1)]
        start_x = np.floor(x)
        start_y = np.floor(y)
        start_z = np.floor(z)

        return sum([image[np.clip(np.floor(start_x + x), 0, image.shape[0]-1).astype('int'),
                          np.clip(np.floor(start_y + y), 0, image.shape[1]-1).astype('int'),
                          np.clip(np.floor(start_z + z), 0, image.shape[1]-1).astype('int')]
                    *weights_x[x]*weights_y[y]*weights_z[z]
                    for x,y,z in itertools.product(range(2),range(2),range(2))])

image_model = Image_knn()
image_model.fit(ball)

fig, ax = plt.subplots(nrows=3,ncols=3)
ax = ax.reshape(-1)

I am going to give an example using different slices where one direction is the z direction and the other is the one containing the bottom left corner and varying points on the bottom right. First the 3d plot indicating where the cuts will be:

Now I calculate the coordinates for the cuts and plot them. This time I can keep the aspect ratio since I use more points for the direction that is longer. Notice that I put the coordinates of the 2nd point in the heading of the plot.
fig, ax = plt.subplots(nrows=3,ncols=3)
ax = ax.reshape(-1)

for i,x in enumerate(np.linspace(0,100,9)):
    p = np.array([0,100])
    q = np.array([100,100-x])
    distance = np.round(np.linalg.norm(q-p)).astype('int')
    t = np.linspace(0,1,distance)
    xy = t.reshape(-1,1)*q+(1-t).reshape(-1,1)*p
    r,s = np.meshgrid(np.arange(100), np.arange(distance))
    x = xy[s][:,:,0].reshape(-1)
    y = xy[s][:,:,1].reshape(-1)
    z = r.reshape(-1)

    out = image_model.predict(x,y,z)
    ax[i].imshow(out.reshape(distance, 100).T, cmap='gray',vmin=0,vmax=1)
    ax[i].set_title(tuple(q.astype('int')))


text:
Q: Sierra / Mail.app workaround for missing "Display in Place / Display as Icon" choices? The "Display in Place / Display as Icon" choice in Mail.app (accessed via a right-click), previously removed from High Sierra, has now also disappeared in Sierra running Mail.app 10.3.
Is there a workaround? I have a 160K one page .pdf attachment that I'd like to display in full.

A: A successful workaround is displaying the visa on your computer, taking a screenshot (command + shift + 4) of the image, and attaching the screenshot to the email. In this case, the screenshot displays fully, showing the image within the email.


text:
Q: Force django UpdateView to create an new object instead I have a model that will be updated throughout its lifetime. I want each update to return a new object based on the old one, rather than update the original. This is to give users the previous object as a reference while ensuring they don't overwrite it. I tried using the same form, which this question suggested might accomplish what I wanted but it didn't (it updated instead). Then I tried overriding the save method to point to my CreateView as in the code below but that told me it needed a CreateView instance as its first argument. Is there a way to get the behaviour I want?
class TriageUpdateView(PermissionRequiredMixin, UpdateView):
    model = Triage
    form_class = TriageForm
    login_url = "/login/"
    permission_required = "myapp.add_triage"

    def form_valid(self, form):
        obj = form.save(commit = False)
        obj.completed_by = self.request.user.person
        return TriageCreateView.form_valid(self, form)

A: I've found a way, though I'm not sure it's the best way. Django decides whether to update or insert in the database by checking for a primary key value. I set this to None in the validation and that's done the trick.
class TriageUpdateView(PermissionRequiredMixin, UpdateView):
    model = Triage
    form_class = TriageForm
    login_url = "/login/"
    permission_required = "myapp.add_triage"

    def form_valid(self, form):
        obj = form.save(commit = False)
        obj.pk = None
        obj.completed_by = self.request.user.person
        return super(TriageUpdateView, self).form_valid(form)

A: Your solution (pk = None) definitely works (and is documented as a feature in the django doc - therefore it should wirk in the future as well), but if you want to do this manually, you can do the following:
In your form_valid(self, form), call a function create_new_triage(form.instance, self.request.user.person) whih does your job. form.incance holds the current instance of the model as entered by the user and you can use its values in a Triage.objects.create() method.
This gives you more control, but if you can do what you want with just setting pk = None, I would stick to that.


text:
Q: Unifying a lot of scalar arrays Is there any more efficient way for unifying a lot of scalar arrays?
<?php

$input=[
    [65455,5,5,4,1,4,45,4],
    [2,1254,5,454,54,545,4],
    //....
];

A: You can cut it down with a trick:
 array_unique(call_user_func_array("array_merge", $input))

By using call_user_func_array the array_merge will be run implicitly with each row of your input array as parameter: array_merge($input[0], $input[1], $input[2], ...)
Though that's one of those occassions where comments are imperative to make up for terseness.

A: If I understand your requirement correctly, you're looking for array_merge.

A: function array_union($arrayOfArrays){
    $output=[];
    foreach ($arrayOfArrays as $a) {
       $output=array_unique(array_merge($output,$a));
    }
    return $output;
}


text:
Q: facebook ios sdk 2.0 stopped working 9/7/2012? We are using ios sdk 2.0 with an oauth dialog.  Everything seemed to be working fine until last few hours.
The dialog comes up and prompts for facebook uname/pword, upon submission the returned page says.... "The page you requested was not found" the "Back to previous page" link does nothing most of the time, although a few times we got an error code 100.
the app asks for publish_stream and email permissions.
Is the sdk 2.0 deprecated completely?
Also, we have been posting through the app a bit and sometimes deleting the posts or the app.  How can we find out facebook is filtering our app?

A: Go to your Facebook app's settings, click "Advanced" then select the "Desktop/Native" radio button in the "Authentication" section.


text:
Q: JMeter constant timers not operating as expected We have 3 distinct sets of requests that we wish to test using Jmeter.
For this we have created 3 samplers to house these 3 sets of requests and we have added a constant timer in each of these 3 samplers.
Each constant timer contains the function "${__Random(X,Y)}" where X,Y are different for each of the 3 samplers.
However when I run the test I can see that for the first few minutes the requests look like they are being sent as per the timers, but after a period the requests come through almost uniformly accross the board which is not correct.
I have uploaded a picture that shows the structure of our test plan and the throughput that we are seeing enter image description here.

A: The timers work as expected, I would say you're getting more or less equal throughput due to your application being overloaded and responding too slow, i.e. i can see response times over 40 seconds.

HTTP is a stateful protocol, it means that JMeter's HTTP Request samplers wait for response prior to sending a new request so my expectation is that you're mostly impacted with response times, not the timers.
So if you replace your real samplers with i.e. Dummy Sampler with static response time of, say, 100 milliseconds

You should see your timers working as expected.

With regards to the application being slow I would recommend investigating the bottleneck, you can start looking at HTML Reporting Dashboard and correlate the increasing load with the increasing response time.
Also make sure to monitor your application under test baseline health metrics, i.e. CPU, RAM, swap, etc. in order to ensure it has enough headroom to operate. It can be done using JMeter PerfMon Plugin or SSHMon Samples Collector


text:
Q: Spring JPA hibernate -Repeated transactions in the API making it slow I am working on an API in spring - JPA - Hibernate application.
API receives List of Orders which needs to be persisted one by one.
Controller method is like below
bulkUpsert(@RequestBody Orders orders){
  for(Order order:orders.getOrders()){
       saveOrUpdateOrder(order);
  }
}

Service Method is below
@Transactional
saveOrUpdateOrder(Order order){
   //do processing and call dao methods to save/update
}

here is my spring config
<bean id="transactionManager"
      class="org.springframework.orm.jpa.JpaTransactionManager"
      p:entityManagerFactory-ref="entityManagerFactory">
    <property name="defaultTimeout" value="${jdbc.defaultTransactionTimeout}"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

web xml:
 <filter>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
  </filter>

Now the issue that I have observing is that as the no of orders passed keep on increasing ,the time to complete the API is exponentially increasing.I wasn't expecting this as I am commiting the orders one by one.
IF first 100 orders take around 10 seconds then 900th-1000th orders take more than 1 minute.
Now If I add entitymanager.clear() just after calling saveOrUpdateOrder in the loop of controller method(bulkUpsert), api becomes electric fast.
Though I am happy that issue is resolved but I am baffled as my understanding doesn't match with what has happened.I was expecting that when transaction commits it will flush all the things and everything will start all again for the next transaction.
Is it not so ?
Does entities still remain in the session even when transaction commits ?

A: In theory you are correct, however as Spring Boot by default enables the OpenEntityManagerInViewInterceptor which enables the open entitymanager in view pattern. This in turn leads you to a single EntityManager per request.
This explains the behavior you see as you expect to get a new and fresh EntityManager per transaction but instead the pre-registered EntityManager is re-used.
You can solve this by disabling the OpenEntityManagerInViewInterceptor. Do this by setting the spring.jpa.open-in-view to false in the application.properties file. This might, however, lead to issues with other code which, probably unknowingly, depends op the open entitymanager in view behavior.


text:
Q: Concatenate and shorten days in a week in Oracle I have Timings columns as
M 8:00 AM - 5:00 PM | Tu 8:00 AM - 5:00 PM | W 8:00 AM - 5:00 PM | Th 8:00 AM - 5:00 PM | F 8:00 AM - 5:00 PM

Would like to generate it as
M-F 8:00 AM - 5:00 PM

Sometimes the timings might change as
M 9:00 am - 9:00 pm | Tu 9:00 am - 9:00 pm | W 9:00 am - 9:00 pm | Th 9:00 am - 9:00 pm | F 9:00 am - 9:00 pm | Sa 9:00 am - 9:00 pm | Su 10:00 am - 6:00 pm

In this case I have to generate as
M-Sa 9:00 am - 9:00 pm | Su 10:00 am - 6:00 pm

A: Have a look at this step-by-step example. Follow comments written within the code.
Take it as a guide to what you might do as this approach won't work properly if there were different time spans somewhere "in the middle" (for example, for Thursday). Groups would still be OK, but days (named in shortened version) would be kind of wrong as you'd get e.g. M-Su 9:00 am - 9:00 pm | Th 9:00 am - 4:00 pm. If that doesn't bother you, fine.
SQL> with
  2  test (id, col) as
  3    (
  4     select 1, 'M 8:00 AM - 5:00 PM | Tu 8:00 AM - 5:00 PM | W 8:00 AM - 5:00 PM | Th 8:00 AM - 5:00 PM | F 8:00 AM - 5:00 PM' from dual union all
  5     select 2, 'M 9:00 am - 9:00 pm | Tu 9:00 am - 9:00 pm | W 9:00 am - 9:00 pm | Th 9:00 am - 9:00 pm | F 9:00 am - 9:00 pm | Sa 9:00 am - 9:00 pm | Su 10:00 am - 6:00 pm' from dual
  6    ),
  7  temp as
  8    -- split column to rows
  9    (select id,
 10            column_value rn,
 11            trim(regexp_substr(upper(col), '[^|]+', 1, column_value)) val
 12     from test join table(cast(multiset(select level from dual
 13                                        connect by level <= regexp_count(col, '\|') + 1
 14                                       ) as sys.odcinumberlist)) on 1 = 1
 15    ),
 16  extr as
 17    -- extract day and time span into separate columns (for aggregating purposes)
 18    (
 19     select id,
 20            rn,
 21            substr(val, 1, instr(val, ' ')) c_day,
 22            substr(val, instr(val, ' ') + 1) c_period
 23     from temp
 24    ),
 25  agg1 as
 26    (-- group values from the previous step
 27     select id,
 28            listagg(trim(c_day), ', ') within group (order by rn) days,
 29            c_period
 30     from extr
 31     group by id, c_period
 32    )
 33    -- the final result
 34  select id,
 35         listagg
 36           (initcap(regexp_substr(days, '^\w+') ||'-'|| regexp_substr(days, '\w+$')) || ' ' || lower(c_period), ' | ')
 37            within group (order by id)
 38            val
 39  from agg1
 40  group by id
 41  order by id;

 ID VAL
--- --------------------------------------------------
  1 M-F 8:00 am - 5:00 pm
  2 M-Sa 9:00 am - 9:00 pm | Su-Su 10:00 am - 6:00 pm

SQL>

Alternatively, instead of shortening it that much, you could name all days that share the same time span, which would return the correct result regardless of which day(s) have a different time span. For example:
 <... snip, as previous lines are not modified ...>
 25  agg1 as
 26    (-- group values from the previous step
 27     select id,
 28            listagg(trim(initcap(c_day)), ', ') within group (order by rn) ||' ' || upper(c_period) val
 29     from extr
 30     group by id, c_period
 31    )
 32    -- the final result
 33  select id,
 34         listagg (val, ' | ') within group (order by id) val
 35  from agg1
 36  group by id
 37  order by id;

 ID VAL
--- ----------------------------------------------------------------------------------------------------
  1 M, Tu, W, Th, F 8:00 AM - 5:00 PM
  2 M, Tu, W, F, Sa 9:00 AM - 9:00 PM | Su 10:00 AM - 6:00 PM | Th 9:00 AM - 4:00 PM

SQL>