text:
Q: Not working Wi-Fi on Ubuntu 20.04.3 I have Lenovo Ideapad 5 with AMD Ryzen 5 CPU for around 2 months, running Ubuntu Desktop 20.04.3 LTS 64-bit. The Wi-Fi section in settings is missing. I can't connect to the internet via internal Wi-Fi card. I have been using external Wi-Fi adapter and docking station as temporary alternative.
Output of command uname -srm is:
Linux 5.11.0-38-generic x86_64

Output of command sudo lshw -C network is:
  *-network UNCLAIMED
       description: Network controller
       product: Realtek Semiconductor Co., Ltd.
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress cap_list
       configuration: latency=0
       resources: ioport:2000(size=256) memory:d0500000-d05fffff
  *-network
       description: Wireless interface
       physical id: 2
       bus info: usb@3:2
       logical name: wlx909a4acb9022
       serial: 90:9a:4a:cb:90:22
       capabilities: ethernet physical wireless
       configuration: broadcast=yes driver=rtl88XXau driverversion=5.11.0-38-generic ip=192.168.1.251 multicast=yes wireless=IEEE 802.11AC

Output of command sudo rfkill is:
ID TYPE      DEVICE      SOFT      HARD
 0 bluetooth hci0   unblocked unblocked
 1 wlan      phy0   unblocked unblocked

Output of command dkmp status is:
8812au, 5.6.4.2_35491.20191025, 5.11.0-37-generic, x86_64: installed
8812au, 5.6.4.2_35491.20191025, 5.11.0-38-generic, x86_64: installed
8812au, 5.6.4.2_35491.20191025, 5.4.0-89-generic, x86_64: installed
rtl8821ce, v5.5.2_34066.20200325, 5.11.0-38-generic, x86_64: installed
rtl8821ce, v5.5.2_34066.20200325, 5.4.0-89-generic, x86_64: installed

Output of command lspci -knn | grep Net -A3; rfkill list is:
03:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. Device [10ec:8852]
    DeviceName: Realtek RTL8111E Ethernet LOM
    Subsystem: Lenovo Device [17aa:4852]
04:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Device [1002:164c] (rev c2)
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

Output of command lspci -nnk | grep -iA3 net is:
03:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. Device [10ec:8852]
    DeviceName: Realtek RTL8111E Ethernet LOM
    Subsystem: Lenovo Device [17aa:4852]
04:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Device [1002:164c] (rev c2)
    Subsystem: Lenovo Device [17aa:3801]

I don't know which one is the correct and which not.
How can i fix this to make it works? What am I supposed to do to fix laptop Wi-fi?


text:
Q: problem w/ 15 char ID's and case-insensitive sorting So here's the deal.  I have a somewhat complex formula field that returns a Campaign ID.  Then I have a SOQL query in apex that needs to ORDER BY this field.  The problem is that ORDER BY is case insensitive, and formula fields by default return the 15 char ID.  (http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_orderby.htm)
Result: if you have two campaign records whose 15-char IDs differ only in character cases, the sort does not work as expected.  This actually cropped up in an installation, took me forever to troubleshoot it.
I thought the fix would be easy.  Just wrap my formula in CASESAFEID() and we're good, right?
But not so fast.  There's something screwy with that function.  My formula before adding CASESAFEID was about 1300 chars according to SF.  (Which is crazy, it's nowwhere near that long and doesn't reference any other formulas, just references related fields via Parent.Field notation.  Basically I have no idea how SF gets their character counts on formulas.)
After wrapping my formula in one CASESAFEID() function it comes out to over 24,000 characters.  Why?  I have no earthly clue.  (Is this a bug?  Should I submit a case?)
So what's the workaround?  I could write a trigger to save the 18 char ID I want to sort on to a text field, but I'd really like to avoid that if possible.  Anyone see any other way out?
This is part of a managed package.

A: This is why i hate the idea of using ID for sorting. I would strongly suggest you to create auto-number field on campaign and use that for ordering.

redpajama_set_name: RedPajamaStackExchange


text:
Q: On music games like Osu! (mania), why are the inputs arrow shaped? In many rhythm games (like step mania, Osu! mania, etc.), the inputs are arrow shaped.  Where does this "standard" of rythm/music games come from ?

A: I can't speak for Osu!mania directly, but Stepmania was based on Dance Dance Revolution (DDR), which had a pad below the player with the 4 directional arrows, which the player had to step on in time with the music.  Stepmania was meant to be an open sourced clone of DDR, so many of it's original mechanics and design would come from the DDR franchise mechanics.
The "step" in stepmania is a reference to how Dance Dance Revolution (and clones like Stepmania) are supposed to be played.  By stepping on the corresponding arrows at the right time to the beat.
As far as I'm aware, with Osu!mania there are just some maps which have this arrow layout.  Wikipedia's page on Osu!mania says:

osu!mania is a game mode which consists of a piano-like style of clicking notes to the beat, similar to the Beatmania IIDX series. The number of keys ranges from 1 to 9, with 4 keys and 7 keys being more popular among players.

So Osu!mania is more of a direct clone of the Beatmania series, which doesn't use the dance pads like DDR was designed for.  I assume that some Osu!mania tracks that only have 4 keys (which it says is a popular format) often map those keys to arrows, so that it resembles the traditional beat games like DDR and Stepmania.
As far as I can tell, the standard of using 4 arrow keys to represent the inputs is because Stepmania is directly based off Dance Dance revolution, and because 4-key Osu!mania levels sometimes pay homage to DDR and Stepmania, as the gameplay is similar.


text:
Q: Необходимо нарезать видео на фото с помощью Xabe.FFmpeg Моя задача заключается в том чтобы каждую 50 мсек сохранять фрагмент видео как фото. Для этого я использую Xabe.FFmpeg. Я указываю ссылку на файл и мне выдают ошибку, при этом ссылку указываю верную.
Код взял из документации но немного изменил, потому что он не работал.
В чем я сделал ошибку?

Func<string, string> outputFileNameBuilder = (number) => { return 'p' + number + ".png"; };
IMediaInfo info = await FFmpeg.GetMediaInfo("test5.mkv").ConfigureAwait(false);
IVideoStream videoStream = info.VideoStreams.First()?.SetCodec(VideoCodec.png);

IConversionResult conversionResult = await FFmpeg.Conversions.New()
    .AddStream(videoStream)
    .ExtractEveryNthFrame(10, outputFileNameBuilder)
    .Start();

UPDATE
P.S. я немного исправил код и понял в чем проблема, но не могу найти файл который нужно указывать тут FFmpeg.SetExecutablesPath
Ошибка:
System.IO.IOException: "Параметр задан неверно.:
'G:\С#\sourc\repos\proj\proj\bin\Debug\net6.0\Xabe.FFmpeg.5.2.0\Xabe.FFmpeg.5.2.0.nupkg'"


text:
Q: chromatic number for $k$-regular graph Let $G$ be a connected graph that is $k$-regular and is neither a complete graph nor an odd cycle. Then the chromatic number of $G$ is $k$. Is it true?

A: No, this is not true. For instance, the utility graph $K_{3,3}$ is cubic, i.e. 3-regular. However, it is also bipartite. It is well-known that a graph is 2-colorable if and only if it is bipartite. So we have a counterexample.


text:
Q: Sort Objects From a File (At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
    int i;
    Employee temp;

    boolean flag = true;

        while(flag)
        {
            flag = false;
            for(i = 0; i < size; i++)
            {

                if (emply[i].getName().compareTo(emply[i+1].getName())>0)
                   {
                       System.out.println(emply[i].getName());
                       temp = emply[i];
                       emply[i] = emply[i+1];
                       emply[i+1] = temp;
                       flag = true;
                   }

            }
        }

}

On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int     prefHours;
String  name;
String  avail;

Employee( String nam, int hours, String aval )
{
    name = nam;
    prefHours = hours;
    avail = aval;
}

void prnEmpl()
{
    System.out.print("Name: " + name);
    System.out.println();
    System.out.print("Prefered hours: " + prefHours);
    System.out.println();
    System.out.print("Availability: " + avail);
    System.out.println();
}

String getName()
{
    return name;
}

String getAvail()
{
    return avail;
}

}

A: Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.


text:
Q: Run two programs and handling I/O by Java server I have two programs ( the language doesn't matter, let's say C++ ) and i have to run and manage the communication between them ( by a server written in Java ) this communication works as follow :
At each step program #1 gets input from the program #2 and after doing some processing on it, it'll create an output and gives it to the program #2 as its input and program #2 do the same thing. After a few steps ( could be like 10 steps ) this communication will be over. there's no delay between these steps and they work immediately.
I've run them through java.lang.Process and for handling the input and output, I'm using InputStream and OutputStream.
The problem is, I have no control over these Programs behavior, So they could damage my server, intentionally or unintentionally, like consuming all the Memory or crashing the entire server.
How can I handle these behaviors and protect my server from crashing ? Is there a better way to do this ?


text:
Q: responsive banner with responsive next/back arrows over the top I want to create a simple 4 slide banner which is 100% width & responsive with 4 responsive buttons underneath to switch between slides, but also as an addition arrows on either side of the banner to jump back and forth between the previous and next slide.
I've built the banner and the functionality works but I can't get the arrows to adjust vertically so they always stay in the vertical middle of the banner. It's probably to do with them being absolute but I don't know any other way of getting them to float over the top of the banner.
Help much appreciated
My code:

                         <

                         >

                         <

                         >

                         <

                         >

                         <

                         >

        1
        2
        3
        4

and a jsfiddle: http://jsfiddle.net/vko2hddn/

A: Actually I've figured it out I was just approaching it incorrectly, I needed to add the arrows to a seperate div on each slide which would be set to absolute and then the arrows would be marginly positioned inside that:
section#homebanner section.slider .arrows {width:100%; position: absolute;}
section#homebanner section.slider .leftarrow {float: left; width: 47px; height: 45px; margin-top: 12%; margin-left: 2%; padding-top: 5px; padding-right: 3px; font-size: 30px; text-align: center; text-decoration: none; color: white; border: 4px solid; border-radius: 100%;}
section#homebanner section.slider .rightarrow {float: right; width: 47px; height: 45px; margin-top: 12%; margin-right: 3%; padding-top: 5px; padding-left: 3px; font-size: 30px; text-align: center; text-decoration: none; color: white; border: 4px solid; border-radius: 100%;}

             <
             >

So it now looks like this: JS http://jsfiddle.net/pcwrvjq0/


text:
Q: Problema al Instanciar App() o AppFactory() Quiero ejecutar el siguiente codigo en php usando el framework slim 4.2
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

// Instantiate App
$app = AppFactory::create();

// Add error middleware
$app->addErrorMiddleware(true, true, true);

// Add route
$app->get('/hello/{name}', function (Request $request, Response       $response, $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});

$app->run();

PHP Fatal error:  Uncaught RuntimeException: Could not detect any PSR-17 ResponseFactory implementations. Please install a supported implementation in order to use `AppFactory::create().
Me sale ese error, ya intente ejecutar distintas variariones de un simple codigo, pero me sigue saliendo este tipo de errores. No encuentro en la documentacion informacion relacionada con este tipo de problemas.
Contenido de composer.json
 {
"require": {
    "slim/slim": "^4.2",
    "slim/http": "^0.7.0"
}
}

A: Te estaría faltando agregar PSR-7.
Solución:
Según la documentación

Para que la detección automática funcione y le permita usar AppFactory::create() y App::run() sin tener que crear manualmente un ServerRequest, necesita instalar una de las siguientes implementaciones:

*

*Slim-Psr7 - Install using composer require slim/psr7

*Nyholm/psr7 & Nyholm/psr7-server - Install using composer require nyholm/psr7 nyholm/psr7-server

*Guzzle/psr7 & http-interop/http-factory-guzzle - Install using composer require guzzlehttp/psr7 http-interop/http-factory-guzzle

*zend-diactoros - Install using composer require zendframework/zend-diactoros

Referencias:

*

*Slim Framework 4.x > Choose a PSR-7 Implementation & ServerRequest Creator


text:
Q: How do I say what I mean for this closure-related code in Swift? My first pass at this is an example of code in JavaScript that looks like it should work, but on closer inspection has different behavior. My Swift code presently has, with SwiftyJSON:
    for(var index = 0; index < datesToLoad.count; index += 1) {
        var formattedDate = formatter.stringFromDate(datesToLoad[index]);
        if (presentLocation["days"][formattedDate] == nil) {
            loadDataFromURL(NSURL:"http://api.sunrise-sunset.org/json?formatted=0&lat=\(presentLocation.coordinate.latitude)&lon=\(presentLocation.coordinate.longitude)&date=\(formattedDate)&formatted=0", completion: {(data, error) -> Void in {
                if (var json = JSON(data:data)) {
                    presentLocation["days"][formattedDate]["sunrise"] = parser(json["results"]["sunrise"]);
                    presentLocation["days"][formattedDate]["sunset"] = parser(json["results"]["sunset"]);
                }
            }
        }
    }

Now what I would expect is for the code not to work as intended. What I want to accomplish is that for each of the formattedDate values for the list, an asynchronous call to retrieve data from a URL is made, and each API call will work with the formattedDate value that was alive when the loadDataFromURL() call was made. What I expect will happen is that the loop will run quickly, spawning a few asynchronous requests, and formattedDate will be available with the last value it was defined. I can probably work around not knowing how to do this properly in Swift, as the data returned from API gives multiple timestamps, but I'd like to know the preferred way to go through multiple values for formattedDate with the callback function seeing the version that was active when its loadDataFromURL() function was called.
I could also get the results I want from completely unrolling the (four element) loop and using separate variable names for each closure-based API call, but I'd really prefer to know what is the right way to deal with this kind of issue.

A: Each pass through the for loop creates a new formattedDate variable which is independent of the formattedDate variable created on any other pass.
Thus your loop should do what you intended.
Playground demo:
import XCPlayground
import UIKit

var blocks: [()->Void] = []

for i in 0..<5 {
    var s = "\(i)"
    blocks.append( { print(s) } )
}

print("calling blocks")

for block in blocks {
    block()
}

Output:
calling blocks
0
1
2
3
4


text:
Q: Sharepoint 2013 delete AttachmentFiles by JS how can I delete an AttachmentFiles of a list item by Javascript?
(with REST or using SP.RequestExecutor)
Thank,Nk

A: REST (with jQuery.ajax):
$.ajax({
  url: "/_api/lists/getByTitle('Test')/getItemById(1)/AttachmentFiles/getByFileName('test.txt')",
  method: 'DELETE',
  headers: {
    'X-RequestDigest': $('#__REQUESTDIGEST').val()
    }
});

You can see the REST API endpoints at http://msdn.microsoft.com/en-us/library/office/jj860569(v=office.15).aspx . And you can see the equivalent for JSOM and CSOM at http://msdn.microsoft.com/en-us/library/office/dn268594(v=office.15).aspx . You see the one I used at the top there.
For example in the first link you know you want ListItem, and then you check the Properties where you will find AttachmentFiles. Although this will not give you the getByFileName method you were seeking. What I did to find this was to actually use the second link above and follow the JSOM example and click methods for SP.AttachmentCollection. I'm not sure why the documentation is lacking this, but you can usually find the same methods in JSOM as in REST (usually).
And as I knew that as long as I got some kind of item I could use the DELETE verb to delete it I just tried that and it worked.
Another simple approach is to simply query against the API and you will see available methods listed out for you, so just playing around with it and traversing downwards step by step helps a lot.

A: You can use the below code
function DeleteItemAttachment(ItemId, FileTitle) {
            var Dfd = $.Deferred();
            var Url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Attachments')/GetItemById(" + ItemId + ")/AttachmentFiles/getByFileName('" + FileTitle + "')  ";
            $.ajax({
                url: Url,
                type: 'DELETE',
                contentType: 'application/json;odata=verbose',
                headers: {
                    'X-RequestDigest': $('#__REQUESTDIGEST').val(),
                    'X-HTTP-Method': 'DELETE',
                    'Accept': 'application/json;odata=verbose'
                },
                success: function (data) {
                    Dfd.resolve(data);
                },
                error: function (error) {
                    Dfd.reject(JSON.stringify(error));
                }
            });
            return Dfd.promise();
        }

Usage:
DeleteItemAttachment(itemId,'File Name').done(function(response){
//do something with response
})


text:
Q: Extract paired lines I've got a txt file like this. There are paired lines email-password and email-hash.
EMAIL:user1@site.com
PASSWORD:pass1
EMAIL:user2@site.com
PASSWORD:pass2
EMAIL:user3@site.com
PASSWORD:pass3
EMAIL:user4@site.com
HASH:qwerty123
EMAIL:user5@site.com
HASH:somehash
EMAIL:user6@site.com
PASSWORD:pass6

I try to extract only email-password lines excluding email-hash lines.
The command isn't working properly in my case sed -e 's/.*EMAIL://' -e 's/.*PASSWORD://' -e "/\b\HASH\b/d" test.txt
Expect the output:
user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

A: Here's another couple of variations:
paste -d :  - - < myfile | awk -F: '$3 == "PASSWORD" {print $2; print $4}'

tac myfile | awk -F: '$1 == "PASSWORD" {print $2; getline; print $2}' | tac

A: pbm identification
As you know sed is a line oriented stream editor, so when the decision to print or not to print lies in another line like in this your case, we need to orchestrate a state machine, and they will need flip flops or variables in this case.
Essentially we need to hold back printing till we see the correct state transition. Like in this case, when we transition from state (email line) -> state(passwd line) only.
Using GNU sed in extended regex mode -E, which makes reading the sed code easier and writing it less prone to backslashitis.
$ sed -Ee '
    /^PASSWORD:/!{h;d;}
    x;G;s/(^|\n)[^:]*:/\1/g
' test.txt

Basic idea is to save the line which isn't a password line in the hold register so that when we actually get to the password line we can use it.
Using GNU awk we essentially code the above sed functionality in awk with the awk variable e serving as the hold register.
$ awk -F: '
    /^PASSWORD:/&&
    ($0=e RS $2)"";{e=$2}
' test.txt

Using GNU grep we use the before option -B to list one line before the password line then remove the dash line generated by grep and assume nobody uses that as a password.
$ < test.txt \
  grep -B1 '^PASSWORD:' |
  grep -Fxve -- | cut -d: -f2-

perl can be used as shown when we pick the next line and then checks made.
$ perl -ne '
    /^EMAIL:/ && ($_ .= <>);
    /\nPASSWORD:/ && print(s/^[^:]+://mgr);
' tes.txt

bash builtins
while IFS=: read -r a p; do
  case $a in
    'PASSWORD') printf '%s\n' "$e" "$p" ;;
    *) e=$p ;;
  esac
done < test.txt

A: Using sed to pull out the lines that we're interested in, and then cut to remove the PASSWORD: and EMAIL: strings from the start of each line:
$ sed -n 'N; /\nPASSWORD:/p' file | cut -d : -f 2-
user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

Using cut here helps keep the sed expression, and therefore the whole command, simple.

A: If the data you want printed can't contain any :s:
$ awk -F':' '$1=="PASSWORD"{print prev ORS $2} {prev=$2}' file
user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

or if it can then either of these would work, just your preference:
$ awk '{prev=curr; curr=$0; sub(/[^:]+:/,"",curr)} /^PASSWORD:/{print prev ORS curr}' file
user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

$ awk -F':' '{tag=$1; sub(/[^:]+:/,"")} tag=="PASSWORD"{print prev ORS $0} {prev=$0}' file
user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

$ awk -F':' '{tag=$1; sub(/[^:]+:/,""); prev=curr; curr=$0} tag=="PASSWORD"{print prev ORS curr}' file
user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

A: If that file is always in that format with EMAIL at the start of every other line:
sed -n 'N;s/^EMAIL:\(.*\n\)PASSWORD:/\1/p'

should do it. Or, to be on the safe side, look for EMAIL: as the start of the record:
sed -n '/^EMAIL:/{N;s/^EMAIL:\(.*\n\)PASSWORD:/\1/p;}'

You could also use pcregrep with its multiline mode:
pcregrep -M -o1 -o2 --om-separator=$'\n' '^EMAIL:(.*)\nPASSWORD:(.*)'

A: sed -n 'N;s/^EMAIL://;s/PASSWORD://p' file

*

*N append next line to pattern space,

*s/^EMAIL:// substitute EMAIL: with nothing,

*s/PASSWORD://p substitute PASSWORD: with nothing and only print if the substitution was successful.

Tested on sample input. Assumption: 1st line is EMAIL:, 2nd is PASSWORD: or HASH:, and repeat.

As a bonus, if there may be blank lines, it is better to use Awk,
awk -F ':' '/^PASSWORD:/{print line;print $2}/^EMAIL:/{line=$2}' file

A: sed "N;s/\n/ /g" filename| awk -F ":" '/PASSWORD/{gsub("PASSWORD","",$2);print $2"\n"$3  }'

output

user1@site.com
pass1
user2@site.com
pass2
user3@site.com
pass3
user6@site.com
pass6

Python
#!/usr/bin/python
m=[]
k=open('filename','r')
for i in k:
    m.append(i.strip())

for j in range(0,len(m),2):
    if "PASSWORD" in m[j+1]:
        print m[j].split(":")[-1]
        print m[j+1].split(":")[-1]


text:
Q: Can anyone help with this (Javascript arrays)? Hi I am new to Netui and Javascript so go easy on me please. I have a form that is populated with container.item data retuned from a database. I am adding a checkbox beside each repeater item returned and I want to add the container item data to an array when one of the checkboxes is checked for future processing.
The old code used Anchor tag to capture the data but that does not work for me.
<!--netui:parameter name="lineupNo" value="{container.item.lineupIdent.lineupNo}" />

here is my checkbox that is a repeater.
<netui:checkBox dataSource="{pageFlow.checkIsSelected}" onClick="checkBoxClicked()" tagId="pceChecked"/>

this is my Javascript function so far but I want to a way to store the container.item.lineupIdent.lineupNo in the array.
function checkBoxClicked()
{
var checkedPce = [];
var elem = document.getElementById("PceList").elements;

for (var i = 0; i < elem.length; i ++)
{
if (elem[i].name == netui_names.pceChecked)
{
if (elem[i].checked == true)
{
//do some code. }
}
}
}

I hope this is enough info for someone to help me. I have searched the web but could not find any examples.
Thanks.

A: var checkedPce = new Array();

//some other code

checkedPce[0] = stuff_you_want_to_add

A: If you merely want to add a value to an array, you can use this code:
var array = [];
array[array.length] = /* your value */;

You may need to use a dictionary approach instead:
var dictionary = {};

function yourCode(element) {
  var item = dictionary[element.id];
  if (item == null) {
    item = /* create the object */;
    dictionary[element.id] = item;
  }

  // Use the item.
}


text:
Q: Android screen coordinates transformation Android screen coordinates are as below:

I want to bring (0,0) at the center of screen from top left corner.
Can anyone support regarding this?

A: Maybe you can operate the canvas of view.
Translating the canvas to center point ->Then draw the image on canvas.


text:
Q: Extracting parent category ID from wiki API using article ID? Using an external tool to parse Wikipedia articles from the dump files(e.g.enwiki-20200401-pages-articles-multistream.xml.bz2) Now, given the parsed object I have for each article I have it's wiki ID, and the Categories as strings
E.g.
{'Title':'The Dark Knight (film)',
'id':4276475,
'Categories':['2008 films',English-language films,'2000s action thriller films',...,]
}

Unfortunately, these categories are too fine-grained, and I'm trying to get (e.g here action thriller films), thus, trying to find the parent categories of each category in the articles list.
Extracting the category was relatively straight-forward:
import wptools
page = wptools.page('The Dark Knight (film)')
categories_and_more = page.get_more()
one_category = wptools.page(categories_and_more.data['categories'][0])

But extracting all the categories that see this category as a sub-category was not straight-forward.

A: This is simple to do once you have categorylinks.sql inside your SQL server. You would just get the rows where cl_from=article_id, and the parent's title would be given by the column cl_to. You can search up the parent's id by getting another table, page.sql, and reverse searching up the id using page_namespace=14 AND page_title=parent_title.
Unfortunately, the dumps are pretty big and importing them can take pretty long. See here for how to speed the imports up: loading enwiki-latest-categorylinks.sql into mysql


text:
Q: How to reach my controller from code-behind I have this Circle ProgressBar that responds to my Slider value changed:
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="530,303,114,303">
        <Grid HorizontalAlignment="Center" VerticalAlignment="Center" Height="153" Width="155">
            <DesignInControl:CircularProgressBar HorizontalAlignment="Center" VerticalAlignment="Center"
             SegmentColor="#FF878889" StrokeThickness="8" Percentage="100" />
            <DesignInControl:CircularProgressBar Name="circleVale" HorizontalAlignment="Center" VerticalAlignment="Center"
             Percentage="{Binding Value, ElementName=slider}" SegmentColor="#026873" StrokeThickness="8" />
        </Grid>
    </StackPanel>
    <Slider x:Name="slider" Maximum="100" Value="0" Width="200" Margin="597,185,227,495" />
    <Label Name="lblCircleProgress" Content="{Binding Value, ElementName=slider}" Margin="698,344,284,343" Foreground="White"

How can I change this value in the code-behind?
I tried to give this control a name property (Name="circleVale") but for some reason I cannot reach it in the code-behind.

A: Your circleVale control should be accessible in the code behind, but apart from that, i think using SetCurrentValue will leave the binding in place.
Can you change any other property of the progressbar from code?

A: You have the property Percentage of your CircularProgressBar  named "circleVale" bound to the slider's Value. In order to change them from the code behind try to set a depdendency property :
    public int SliderValue
    {
        get { return (int)GetValue(SliderValueProperty); }
        set { SetValue(SliderValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SliderValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SliderValueProperty =
        DependencyProperty.Register("SliderValue", typeof(int), typeof(MainWindow), new PropertyMetadata(0));

    private void btnChangeSliderValue_Click(object sender, RoutedEventArgs e)
    {
        SliderValue = 70;
    }

Set the DataContext of your Window in the constructor:
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

And this can be an example for your XAML:
    <StackPanel>
        <Slider x:Name="slider" Maximum="100" Value="{Binding SliderValue}" Width="200"/>
        <Button Click="btnChangeSliderValue_Click" HorizontalAlignment="Center" Content="Change slider value" Margin="5,10"/>
    </StackPanel>

This way you don't need to access the slider using its name. Using binding is easier and step by step you can reach MVVM.


text:
Q: How to print a X with two letters inside a square I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.
P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q

int main()
{
    int loopLimit = 7;
    int upperCharacter = 0;

    do {
        int loopCounter = 0;

        do {
            if (loopCounter == upperCharacter) std::cout << "P ";
            else std::cout << "p ";
            loopCounter = loopCounter + 1;
        } while (loopCounter < loopLimit);

        upperCharacter = upperCharacter + 1;
        loopLimit = loopLimit - 1;
        std::cout << "\n";
    } while (loopLimit > 0);
}

My code currently outputs:
P p p p p p p
p P p p p p
p p P p p
p p p P
p p p
p p
p

A: With How do I ask and answer homework questions? in mind,
I propose to try the following, in order to avoid that you program yourself into a corner.
Use two nested loops (I'd prefer for but if you are more confident with do while stay with that) to output a square of all the same letters. Do not change those loops afterwards.
Then use an if-else to select between two letters.
Then use an if-elseif-else to select between three.
Then four.
I believe the trick you are supposed to learn here is making conditions. Complex structures of interdependent loops is an alternative, but my guess is that it would make things harder for you.
I think a suitable sequence of letters to get right here would be:

*

*p

*Q on full first diagonal

*q

*P on full other diagonal, but check first diagonal afterwards

*Q on the other half of the second diagonal

Note that getting the order of the conditions right is important, e.g. for the point of diagonal crossing.

A: A pen and a paper solved this question.
Here's the solution:
for (int satirSayaci = 1; satirSayaci < 8; satirSayaci++) {
        for (int karakterSayaci = 1; karakterSayaci < 8; karakterSayaci++)
        {
            if (karakterSayaci >= 8 - satirSayaci) {
                if (karakterSayaci == 8 - satirSayaci || karakterSayaci == satirSayaci) std::cout << "X ";
                else std::cout << "x ";
            } else {
                if (karakterSayaci == satirSayaci) std::cout << "P ";
                else std::cout << "p ";
            }
        }

        // Yeni bir satir yazdir
        std::cout << std::endl;
    }


text:
Q: Why are certain objects loaded into Buffer? I have been experimenting on my test environment with clearing buffer cache via
DBCC DROPCLEANBUFFERS
Before any work is done or operational queries run the buffer is instantly starting to repopulate with data from core tables (data warehouse). It is loading one dimension fully (3 years data) whist others are ignored or only partially loaded so for example

*

*Tab1 1490476 of 1490525 pages loaded (100%) (60m+ row dim)

*Tab2 86446 of 12737347 pages loaded (0.68%) (250m row+ fact)

*Tab3 14 of 18 pages loaded (77.78%) (800 row dim)

Tab1 would rarely have all rows read and updates/inserts would only occur on approximately the last 20% where as Tab3 would be 100% read pretty much all the time but rarely updated/inserted.
Interestingly when I test in a dev environment no data is reloaded in buffer until queries start to be run at which point I see a far different profile

*

*Tab1 89154 of 512569 pages loaded (17.39%)

*Tab2 105652 of 289851 pages loaded (36.45%)

*Tab3 18 of 18 pages loaded (100%)

These were just random reports and a couple of builds run against dev to get these figures but still fairly true to typical usage. The test environment did not change other than a higher dirty row count.
I am curious as to whether the buffer is being reloaded from something like the plan cache or is there something else i should be looking at?
The reason for this question is that I have a performance problem in production where there are significant IO waits when loading Tab2 and I am perplexed as to why Tab1 is being fully loaded despite limited use and in my simple mind a higher buffer % for Tab2 would make more sense.
2017-02-24
There were a couple of queries being passed down that were highlighted by BlitzCache on read sort that were reading an unnecessary amount of data from Tab1 but it also reads from Tab4 equally unnecessarily (Both joined from another table on Surrogate key in the read).
Tab4 pages are however 0.34% written to buffer which I would assume would have been higher if this was the cause of the high buffer content of Tab1.
There were some other issues highlighed by BlitzCache which I will investigate more fully but still at a bit of a loss here.

A: First, check the plan cache with queries that hit sys.dm_exec_query_stats. My favorite is the open source sp_BlitzCache (disclaimer: I'm one of the coauthors). Queries could be running outside of your control, like monitoring systems. I've seen third party tools that do things like check table fragmentation.
Next, not everything stays in the plan cache. Unfortunately - especially when you're dealing with monitoring software - some queries are smart enough to do a WITH (RECOMPILE) in order to avoid going into the plan cache. (sp_BlitzCache even does this.) To catch diabolical queries like this, consider doing a Profiler trace or Extended Events capture - although I wouldn't recommend leaving those in place long term. Only do it to satisfy your curiosity.

A: One possible reason for seeing something like this is that SQL Server may be doing maintenance operations behind the scenes. For example, if you had the AUTO_UPDATE_STATISTICS_ASYNC option set to yes for a database and kicked off a query that encountered stale stats then SQL Server defers the stats update to a background process. If you issued DBCC DROPCLEANBUFFERS after the query plan compilation but before the stats update happened it could appear that SQL Server would be loading data into the buffers without you requesting it.
I don't know how to find a complete list but remember that SQL Server loads data into memory before it can use it. So any maintenance operation that reads data could affect what's in the buffers. To give a few more examples, I expect that ghost record cleanup would have some effect on the buffers. I would also expect that the tuple mover for CCIs would also have some effect on the buffers. There are undoubtedly many other operations that go on behind the scenes.


text:
Q: What does the Atomics object do in JavaScript? This is the MDN documentation on Atomics.
I can't understand how an atomic object could be used in a real-life situation or if they are for internal use only (i.e. not meant to be called at all).
What does the Atomics object do in JavaScript? How can I use them?

A: Dangers of multithreaded programming

*

*Deadlocks

*Unpredictable
  order of read-write operations

*Data fragmentation

To solve the previous problem what can we do?
Use the atomic option
The Atomics object provides atomic operations such as add, sub, and, or, xor, load, store etc. as static methods. They are used with SharedArrayBuffer objects.
For more information and a good example:
Source:https://www.slideshare.net/barakdrechsler/atomic-javascript
https://jirak.net/wp/introducing-new-javascript-optimizations-webassembly-sharedarraybuffer-and-atomics-in-edgehtml-16/
https://www.geeksforgeeks.org/atomics-or-in-javascript/
For good resource  chapter 12 SharedArrayBuffer in:
Phang, C. L. (2017). An Effective Guide to Modern JavaScript:(ECMAScript 2017/ES 8). Chong Lip Phang.

<iframe frameborder="0" scrolling="no" style="border:0px" src="https://books.google.com.tw/books?id=--gvDwAAQBAJ&lpg=PP3&ots=zqgshUnSQa&dq=atomic%20%20SharedArrayBuffer%20%20for%20javascript&lr&pg=PA80&output=embed" width=500 height=500></iframe>

A: This feature was introduced with ECMAScript 2017. Shared Memory and Atomics introduce a new memory model that allows multi-agent programs to communicate using atomic operations that ensure a well-defined execution order even on parallel CPUs. This specification also includes new static methods on Object: Object.values, Object.entries, and Object.getOwnPropertyDescriptors.
The main idea is to bring some sort of multi-threading feature to JavaScript so that JS developers can write high-performance, concurrent programs in the future by allowing to manage memory by themselves instead of letting JS engine manage memory.
This is done by a new type of a global object called SharedArrayBuffer that essentially stores data in a shared memory space. So this data can be shared between the main JS thread and web-worker threads.
You simply use SharedArrayBuffer and the data is instantly accessible by both the main thread and multiple web-worker threads.
But sharing memory between threads can cause race conditions. To help avoid race conditions, the Atomics global object is introduced. Atomics provides various methods to lock the shared memory when a thread is using its data. It also provides methods to update such data in that shared memory safely.
Let's wait some new abstract library which will use those API's right.
shared memory and atomics
a cartoon intro to SharedArrayBuffers
JavaScript: From Workers to Shared Memory
ECMAScript 2019. Memory Model
Avoiding race conditions in SharedArrayBuffers with Atomics
Also recommend to see the tutorial about shared memory in ECMAScript.


text:
Q: Getting the difference in minutes between two date columns I have a file which contain two columns(start date time and end date time) I want to calculate the difference between these dates(in Mins). and store the difference in another column.
Source File
20121224 22:16:10|20121224 23:03:34

Output File
20121224 22:16:10|20121224 23:03:34|73

Can anyone help on this. Any help is appreciated.
Please tell me what is the problem in below command
echo "20121224 22:16:10|20121224 23:03:34"|awk -F'|' '{"date -d "$1" +%s"|getline d1;"date -d "$2" +%s"|getline d2;print $1"|"$2"|"d2-d1}'

I am getting below error while executing the command
sh: +%s: command not found

Please help me !!

A: your example output is not correct.
20121224 23:03:34
20121224 22:16:10

tell me why the diff (in min) is 73? it should be anyway less than 60!
here is an awk oneliner working for your problem:
awk -F'|' -v q='"' '{"date -d"q $1 q" +%s"|getline d1;"date -d"q $2 q" +%s"|getline d2;print $0"|"(d2-d1)/60}' file

test with your example:
kent$  echo "20121224 22:16:10|20121224 23:03:34"|awk -F'|' -v q='"' '{"date -d"q $1 q" +%s"|getline d1;"date -d"q $2 q" +%s"|getline d2;print $0"|"(d2-d1)/60}'
20121224 22:16:10|20121224 23:03:34|47.4

A: #!/usr/bin/perl

use strict;
use warnings;

use DateTime                   qw( );
use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
    pattern => '%Y%m%d %H:%M:%S',
);

open(FILE,"<your_file_name_with_path>");

while(<FILE>)
{
my @arr=split /|/,$_;
difference_mins $arr[0] $arr[1]

}

sub difference_mins
{
my ($istart,$istop)=($_[0],$_[1]);
my $start = $format->parse_datetime( $_[0] );
my $stop  = $format->parse_datetime( $_[1] );

$_->set_time_zone('local') for $start, $stop;
print "$istart | $istop | ";
print( $start->delta_ms($stop)->in_units('minutes'), "\n" );
}

*

*NOTE: This is not tested though.

A: awk -F '|' -v OFS='|' '
    function parse_date(d) {
        gsub(/:/, " ", d)
        return mktime(substr(d,1,4) " " substr(d,5,2) " " substr(d,7))
    }
    {
        diff = int((parse_date($1) - parse_date($2)) / 60)
        diff *= (diff < 0) ? -1 : 1   # awk is missing abs()
        print $0, diff
    }
' << END
20121224 22:16:10|20121224 23:03:34
END

20121224 22:16:10|20121224 23:03:34|47


text:
Q: C calculator program is outputting 0 Trying to make a simple program that calculates the amount of weight lost over a given amount of days using a constant variable. Everything looks right to me but it's outputting 0 as the answer? Any help would be much appreciated!
#include <stdio.h>
#include <stdlib.h>

int main(){

double days; //declaring variables that will be enetred by user
const float weightLoss = 0.04; //declaring constant to be used in calculation
float overallLoss; //float that is used to display overall result

printf("Please enter how many days you are going to fast for: \n");
scanf("%f", &days); //scans keyboard for input and assigns to designated variable
printf("You entered: %f\n", days);

overallLoss = days * weightLoss;

printf("You will lose %.2f stone", overallLoss); //print of the final result

}

A: You have double days;, so you need scanf("%lf", &days).  Or you can use float days; with the current format.
With printf(), you don't need the l; with scanf(), it is crucial.
Don't forget to end outputs with a newline; your last printf() is missing one.  Also, some compilers (GCC and clang, for example) will provide warnings about such mismatches between the format string and the types provided.  Make sure you're using the appropriate options (gcc -Wall, for example) to get them diagnosed.
Working code
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    double days;
    const float weightLoss = 0.04; // Dimension: stone per day
    float overallLoss;

    printf("Please enter how many days you are going to fast for: ");
    if (scanf("%lf", &days) != 1)
    {
        fprintf(stderr, "Oops!\n");
        exit(1);
    }
    printf("You entered: %13.6f\n", days);

    overallLoss = days * weightLoss;

    printf("You will lose %.2f stone\n", overallLoss);

    return 0;
}

Sample output
First run:
Please enter how many days you are going to fast for: 12
You entered:     12.000000
You will lose 0.48 stone

Second run:
Please enter how many days you are going to fast for: a fortnight
Oops!

You can forego the if test if you've not learned about those yet as long as you type the input accurately; it must be a recognizable number.
Alternative code
Using float days instead of double days.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    float days;
    const float weightLoss = 0.04; // Dimension: stone per day
    float overallLoss;

    printf("Please enter how many days you are going to fast for: ");
    if (scanf("%f", &days) != 1)
    {
        fprintf(stderr, "Oops!\n");
        exit(1);
    }
    printf("You entered: %13.6f\n", days);

    overallLoss = days * weightLoss;

    printf("You will lose %.2f stone\n", overallLoss);

    return 0;
}

Sample output
Please enter how many days you are going to fast for: 10
You entered:     10.000000
You will lose 0.40 stone


text:
Q: Emulators for Windows 10 Mobile not available to install I'm using Visual Studio 2015 Professional Update 3 and I'm trying to modify VS and add Emulators for Windows 10 Mobile.
Unfortunately, it doesn't list Emulators for Windows 10 Mobile as an option.

Note: I am using remote desktop to connect to the computer.  Hype-v is enabled.

A: Found the problem.  I verified the following was setup:

*

*Intel VT was enabled on the BIOS

*Verified Hyper-V feature was not enabled on Windows 10

*Manually installed the intelhaxm-android.exe
More Info: https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
Once those were installed/enabled and/or verified, I was able to modify VS2015 and see the features.


text:
Q: Heroku deploy failing? Probably because of dependencies remote: -----> Installing dependencies
remote:        Installing node modules
remote:        npm ERR! code ERESOLVE
remote:        npm ERR! ERESOLVE could not resolve
remote:        npm ERR!
remote:        npm ERR! While resolving: react-rss@2.0.1
remote:        npm ERR! Found: react@18.2.0
remote:        npm ERR! node_modules/react
remote:        npm ERR!   react@"^18.2.0" from the root project
remote:        npm ERR!   peer react@"^18.0.0" from @testing-library/react@13.4.0
remote:        npm ERR!   node_modules/@testing-library/react
remote:        npm ERR!     @testing-library/react@"^13.4.0" from the root project
remote:        npm ERR!   4 more (react-dom, react-router, react-router-dom, react-scripts)
remote:        npm ERR!
remote:        npm ERR! Could not resolve dependency:
remote:        npm ERR! peer react@"^16.13.1" from react-rss@2.0.1
remote:        npm ERR! node_modules/react-rss
remote:        npm ERR!   react-rss@"^2.0.1" from the root project
remote:        npm ERR!
remote:        npm ERR! Conflicting peer dependency: react@16.14.0
remote:        npm ERR! node_modules/react
remote:        npm ERR!   peer react@"^16.13.1" from react-rss@2.0.1
remote:        npm ERR!   node_modules/react-rss
remote:        npm ERR!     react-rss@"^2.0.1" from the root project
remote:        npm ERR!
remote:        npm ERR! Fix the upstream dependency conflict, or retry
remote:        npm ERR! this command with --force, or --legacy-peer-deps
remote:        npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
remote:        npm ERR!
remote:        npm ERR! See /tmp/npmcache.zVSUf/eresolve-report.txt for a full report.
remote:
remote:        npm ERR! A complete log of this run can be found in:
remote:        npm ERR!     /tmp/npmcache.zVSUf/_logs/2022-11-03T19_15_38_788Z-debug-0.log
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        Some possible problems:
remote:
remote:        - Node version not specified in package.json
remote:          https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app.
remote:
remote:  !     Push failed
remote:  !
remote:  ! ## Warning - The same version of this code has already been built: ea132e7d82ff4a3fe3121b0858e49a2c8336bec0
remote:  !
remote:  ! We have detected that you have triggered a build from source code with version ea132e7d82ff4a3fe3121b0858e49a2c8336bec0
remote:  ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote:  !
remote:  ! If you are developing on a branch and deploying via git you must run:
remote:  !
remote:  !     git push heroku <branchname>:main
remote:  !
remote:  ! This article goes into details on the behavior:
remote:  !   https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: !       Push rejected to tb-work-hub.
remote:
To https://git.heroku.com/tb-work-hub.git
 ! [remote rejected] master -> master (pre-receive hook declined)

I don't understand this. It was working just fine yesterday. I'm guessing it's to do with some dependencies I was trying to work with?
If there isn't a clean solution, is there a good way to restore my app without having to start fresh, reinstall everything and copy-paste the src?
Tried: npm uninstall react-rss

A: Go to the app in Heroku -> settings -> Reveal Config Vars
Add a new config var with the key: NPM_CONFIG_LEGACY_PEER_DEPS and value true, and then redeploy.
(Heroku Shopify Application Error 'npm ERR! ERESOLVE unable to resolve dependency tree')
I hope it works.


text:
Q: java.lang.ArrayIndexOutOfBoundsException: 2 I'm trying to connect java to sql. Though I'm a newbie with javam I can't seem to find out why.
java.lang.ArrayIndexOutOfBoundsException: 2

Can you help me and give me idea how to figure it out?
try{
       Connection con = dbConnection();

       String lname = this.last.getText();
       String fname = this.first.getText();
       String mname = this.mid.getText();
       String ad = this.add.getText();
       String bd = this.bday.getText();
       String ag = this.edad.getText();
       String nom = this.no.getText();
       String per = this.person.getText();

       String query = "INSERT INTO Personal Category    (Lastname,Firstname,Middle,Address,Birthday,Age,No,Person) VALUES (?,?)"; //to insert to database

       PreparedStatement pre;

       pre = con.prepareStatement(query);

       pre.setString(1, lname);
       pre.setString(2, fname);
       pre.setString(3, mname);
       pre.setString(4, ad);
       pre.setString(5, bd);
       pre.setString(6, ag);
       pre.setString(7, nom);
       pre.setString(8, per);

       pre.execute();//execute

       con.close();

    }catch (Exception e){

        System.out.println(e);

    }

}

A: You cannot set more prepared statement properties than you have '?' in your query.
"ArrayIndexOutOfBoundsException: 2" means it fails at the third setString (the internal array is zero-based as all java arrays), which is normal given you have only two '?' in the query.
EDIT :
You probably have an error due to the space in your table name. Try with
INSERT INTO [Personal Category]    (Lastname, ...

A: You only have two ? in your VALUES() declaration.  You need to have as many as you have column names.
Try
String query = "INSERT INTO Personal Category    (Lastname,Firstname,Middle,Address,Birthday,Age,No,Person) VALUES (?,?,?,?,?,?,?,?)"; //to insert to database

A: You need more question marks - six more, to be precise.
String query = "INSERT INTO Personal Category    (Lastname,Firstname,Middle,Address,Birthday,Age,No,Person) VALUES (?,?,?,?,?,?,?,?)";

JDBC interprets each question mark as a placeholder for a parameter, i.e. a promise by your program to supply a value after preparing the statement. When you call setString, setInt, setLong, etc. on your prepared statement, a corresponding numbered placeholder must exist. Otherwise, java.lang.ArrayIndexOutOfBoundsException is thrown.

A: You should have as many placeholders (?) as the number of parameters to be passed to that INSERT statement.
String query = "INSERT INTO PersonalCategory (Lastname, Firstname, Middle, " +
"Address, Birthday, Age, No, Person) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"

A: String query = "INSERT INTO Personal Category    (Lastname,Firstname,Middle,Address,Birthday,Age,No,Person) VALUES (?,?)";
The problem is with the Number of arguments to be passed in the VALUES, You have passed only 2 arguments where it needs to be 8.

A: you have got the answer to "ArrayIndexOutOfBound" issue. I will answer to your second question "SQLException" and give some advice to improve your code.
That SQLException is happening because your table name I guess. There are 2 words in your table name and that might the confusing the compiler.
Advices

*

*you are executing preparedStatement without catching its output value. It will give you an boolean value as the output. Then only you can find what kind of thing has been executed.

*In here, it seems like you are ONLY INSERTING data, and you are sure you are ONLY INSERTING DATA. So, if it is, use executeUpdate() rather than execute() method.

*Always close the connection inside a final() block. This way, you can always make sure the connection is closed whether the code fails or not. By doing this, Database rush will be managed smoothly, by not keeping unnecessary connections open.
Lets stay with good software engineering concepts :)


text:
Q: Powershell context menu shortcuts such as CTRL+M don't work I often use the mark function in powershell. The context menu says that the short-cut is Ctrl+m.

However, pressing Ctrl+m doesn't seem to work. It just inputs ^M. The strange thing is that Ctrl+c does work and does not print anything.
In the context menu properties I've enabled ctrl key shortcuts.

I've also tried disabling it, to no avail. There does not seem to be much more I can do. How do I get the Ctrl+m shortcut to work in powershell? (The alternative is Alt+Space+e+m which does work but isn't really userfriendly)

A: A bit of a workaround - but it works for me:
At the Powershell prompt, type cmd, hit enter - this will launch command prompt - then ctrl+m works. When you are done you can type "exit" and it will return to powershell.


text:
Q: vagrant: can I `vagrant up` just one machine from multi-machine setup can I vagrant up just one machine from multi-machine setup?
or
how could I have different setups for developing e.g. local, test and production? do I have to have different Vagrantfiles?
example Vagrantfile (taken from Multi-Machine Doc page)
Vagrant.configure("2") do |config|
  config.vm.provision "shell", inline: "echo Hello"

  config.vm.define "web" do |web|
    web.vm.box = "apache"
  end

  config.vm.define "db" do |db|
    db.vm.box = "mysql"
  end
end

A: *

*To start desired machine just call vagrant up machine_name.
In your config it could be vagrant up web.

By setting autostart: false in machine configuration, you block autostart of the machine in vagrant up call. More about vagrant multi-machine configuration here.
2.There are many ways to have different setups in vagrant.
a. Define different machines with different provisions scripts :
  config.vm.define "m1", autostart: false do |m1|
    m1.vm.provision "shell" do |s|
        s.path = "path_to/m1_provision_script.sh"
    end
  end
  config.vm.define "m2", autostart: false do |m2|
    m2.vm.provision "shell" do |s|
        s.path = "path_to/m2_provision_script.sh"
    end
  end

b. Provide different parameter to provision script:
  config.vm.define "m1", autostart: false do |m1|
    m1.vm.provision "shell" do |s|
        s.path = "path_to/provision_script.sh"
        s.args = "machine_1"
    end
  end
  config.vm.define "m2", autostart: false do |m2|
    m2.vm.provision "shell" do |s|
        s.path = "path_to/provision_script.sh"
        s.args = "machine_2"
    end
  end

c. If you are using puppet as a provisioner, you can also define custom fact the will indicate if machine is local, test or prod.


text:
Q: Extract Image Link with Nokogiri and Xpath I am trying to use xpath and nokogiri to extract the image URL of google images. when I right-click an image and copy its xpath, I get the following:
//*[@id="irc_cc"]/div[3]/div[1]/div[1]/div[2]/div[1]/a/img
However, when I put this into the nokogiri xpath call, nothing returns. Any ideas on how I might capture the URL to the image? Thank you!
require "open-uri"
require "mechanize"
require "net/http"

base_url = "https://www.google.com/search?
tbm=isch&tbs=isz:lt,islt:vga&q=Analog%20Bar%20San%20Diego%20Burgers"

doc = Nokogiri::HTML(open(base_url))
doc.xpath('//*[@id="irc_cc"]/div[3]/div[1]/div[1]/div[2]/div[1]/a/img').each do |node|
  puts node
end


text:
Q: Android Studio "unused import" message when putting SDK inside build.gradle I'm trying to insert an SDK called Mesibo for communication, and in my project it instantly greys out when I try to import: import com.mesibo.api.mesibo; with the message cannot resolve symbol 'mesibo' and unused import around it
This is the build.gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.richard.myapplication"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'com.mesibo.api:mesibo:1.0.5'
    implementation 'com.mesibo.api:calls:1.0.3'
    implementation 'com.mesibo.api:ui:1.0.4'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

import com.mesibo.api.mesibo;

I'm following their documentation, and the import stops gradle from syncing with the project for some reason. I'm very new to Android Studio and this is my first time attempting to place an SDK + API in.

A: This goes in your Java/Kotlin code, not in Gradle
import com.mesibo.api.mesibo;

So remove it from there, and then compile the code, then add it to the other source files you need this class.
And I think that their documentation is very poor... should be
import com.mesibo.api.Mesibo;

https://github.com/mesibo/samples/tree/master/android/MesiboSample/app/src/main/java/com/mesibo/firstsample


text:
Q: Javascript expression to define object's property name? I'd like to create this object...
object = {
  'object[1][var_name_1]' : 'value1',
  'object[1][var_name_2]' : 'value2',
};

I'm trying to it this way, but I'm getting error missing : after property id...
function getPrefix() {
  return 'object[1]';
}

object = {
  getPrefix() + '[var_name_1]' : 'value1',
  getPrefix() + '[var_name_2]' : 'value2',
}

What am I doing wrong? Or maybbe it is impossible to set object property name using js experession?
Thank you

A: You cant set variable properties using literal syntax, but you can set properties using [], after you've created the object:
myObject = {}
myObject["any_string_here"] = myValue

A: In an object literal, each property name can only be identifier rather than an expression, which means you can't use variables. You can only use the square bracket notation on an existing object, so if you have a variable you wish to use as a property name then you'll need to do it after the object is created:
var object = {
    '1': {};
};

object[1][var_name_1] = 'value1';
object[1][var_name_2] = 'value2';


text:
Q: iOS Draw Circle which is Clickable I am drawing a circle using "CGContextAddEllipseInRect" method. After that I want to handle some events on click of the circle.
Not getting any methods for this.
Please help me.

A: I know this question is old but I wanted to throw my two cents out there anyway. I think what you're trying to accomplish is much easier using a button, as Jennis suggests. However, his button wasn't very round.
The property that needs to be changed to make a button round is .cornerRadius. Here's how this can be done using Jennis' code sample:
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.layer.backgroundColor = [UIColor colorWithWhite:0.2f alpha:.5f].CGColor;
    button.frame = CGRectMake(x, y, width, height);
    button.layer.cornerRadius = 20; //key to rounded button
    [[self view] addSubview:button];
    [button addTarget:self action:@selector(yourEventTobeFired) forControlEvents:UIControlEventTouchUpInside];

And the resulting output of this code:

This button is clickable, and upon clicking it will call the method yourEventTobeFired
If you refuse to use a button, then I'd suggest adding a gesture recognizer to your custom drawing, as I don't believe you can add an action like you can a button.

A: Assuming you are drawing this circle in UIView, You can create Custom Button and add it to your view .
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 30);
[yourView addSubView:button];
[button addTarget:self action:@selector(yourEventTobeFired) forControlEvents:UIControlEventTouchUpInside];

Thats it.


text:
Q: Finite Double Sum $\sum_{j=0}^n\sum_{i=0}^j \binom {n+1}{j+1}\binom ni =2^{2n}$ The problem is given in a combinatorics class study sheet. I cannot prove, and actually I am not sure if there was a mistake in the question or not. I tried for a few small n's e.g. 1, 2 and it holds. $\\$
I need to show that $\\$ $\mathop{\sum_{j=0}^{n}\sum_{i=0}^{j}}$ $n+1 \choose j+1$ $n \choose i $ = $2^{2n}$  $\forall n$ $\in$ $\mathbb{Z}^{+}$

A: We give a probabilistic interpretation. By changing from probabilities to counts, we get a combinatorial interpretation.
Alicia tosses a fair coin $n+1$ times, and Beti tosses a fair coin $n$ times. Alicia wins if she has more heads than Beti.
Our double sum, divided by $2^{2n+1}$, gives the probability that Alicia wins. We will show that this probability is $\frac{1}{2}$.  Then multiplying by $2^{2n+1}$ yields our desired result.
Imagine that the two players each toss their coins simultaneously $n$ times. If Alicia is leading after $n$ tosses, she will win. If Beti is leading after $n$ tosses, then Beti will win. By symmetry these two events are equally likely.
And if they are tied after $n$ tosses, then with probability $\frac{1}{2}$, Alicia will get a head on the $(n+1)$-th toss, and win. And with probability $\frac{1}{2}$ she will get a tail and lose.

A: The identity as shown in the question is correct.
$$\begin{align}
\sum_{j=0}^n\sum_{i=0}^j\binom {n+1}{j+1}\binom ni
&=\sum_{j=0}^n\sum_{i=0}^j\binom {n+1}{j+1}\binom n{n-i}\\
&=\sum_{j=0}^n\sum_{r=0}^j\binom {n+1}{j+1}\binom n{n+r-j}
&&\text{(putting }r=j-i)\\
&=\sum_{r=0}^n\sum_{j=r}^n\binom {n+1}{j+1}\binom n{n+r-j}
&&\text{(swapping order of indices)(}0\le r\le j\le n )\\
&=\sum_{r=0}^n\binom {2n+1}{n+1+r}
&&\text{(Vandermonde)}\\
&\color{lightgrey}{=\frac 12 \sum_{r=0}^n\binom {2n+1}{n-r}+\binom {2n+1}{n+1+r}}\\
&\color{lightgrey}{=\frac 12 \sum_{r=0}^{2n+1} \binom {2n+1}r}\\
&=\frac 12 \cdot 2^{2n+1}\\
&=2^{2n}\qquad\blacksquare\end{align}$$

Another approach:
$$\begin{align}
\sum_{j=0}^n\sum_{i=0}^j\binom {n+1}{j+1}\binom ni
&=\sum_{j=0}^n\sum_{i=0}^j \left[\binom nj+\binom n{j+1}\right]\binom ni\\
&=\underbrace{\sum_{\large 0\le i\color{red}\le j\le n}\binom nj\binom ni}_*+\binom n{j+1}\binom ni\\
&=\overbrace{\sum_{\large 0\le i\color{red}= j\le n}\binom nj\binom ni+\sum_{\large 0\le i\color{red}<j\le n}\binom nj\binom ni}^*+\sum_{\large 0\le i\color{red}< j\le n}\binom nj\binom ni\\
&=\sum_{\large 0\le i\color{red}=j\le n}\binom nj\binom ni+2\sum_{\large 0\le i\color{red}< j\le n}\binom nj\binom ni\\
&=\sum_{\large 0\le i\color{red}=j\le n}\binom nj\binom ni+\sum_{\large 0\le i\color{red}\neq j\le n}\binom nj\binom ni&&\text{(by symmetry)}\\
&=\sum_{j=0}^n\sum_{i=0}^n\binom nj\binom ni&&\text{(**)}\\
&=\sum_{j=0}^n\binom nj\sum_{i=0}^n\binom ni\\\\
&=2^n\cdot 2^n\\\\
&=2^{2n}\qquad\blacksquare
\end{align}$$
** as pointed out by Alex in a comment on the original question!

A: Here is another variation of the theme based upon two observations.

The first observation is the calculation of the double sum of the complete region $$0\leq i,j\leq n$$ is simple.
\begin{align*}
\sum_{j=0}^n\sum_{i=0}^{n}&\binom{n+1}{j+1}\binom{n}{i}\\
&=\sum_{j=1}^{n+1}\binom{n+1}{j}\sum_{i=0}^{n}\binom{n}{i}\tag{1}\\
&=\left(2^{n+1}-1\right)2^n\\
&=2\cdot4^n-2^n
\end{align*}

Comment:

*

*In (1) we rearrange the double sum and shift the index $j$ by one.

The second observation is based upon symmetry. We could expect the expression of the double sum with the upper triangle $$0\leq j < i\leq n$$ as index range is very similar to the expression with the lower triangle $$0\leq i\leq j \leq n$$ as index range. Indeed, we obtain
  \begin{align*}
\sum_{j=0}^{n}&\sum_{i=j+1}^n\binom{n+1}{j+1}\binom{n}{i}\\
&=\sum_{j=0}^{n}\sum_{i=n-j+1}^n\binom{n+1}{n-j+1}\binom{n}{i}\tag{2}\\
&=\sum_{j=0}^{n}\sum_{i=0}^{j-1}\binom{n+1}{n-j+1}\binom{n}{i+n-j+1}\tag{3}\\
&=\sum_{j=1}^{n}\sum_{i=0}^{j-1}\binom{n+1}{j}\binom{n}{i}\tag{4}\\
&=\sum_{j=0}^{n-1}\sum_{i=0}^{j}\binom{n+1}{j+1}\binom{n}{i}\tag{5}\\
&=\sum_{j=0}^{n}\sum_{i=0}^{j}\binom{n+1}{j+1}\binom{n}{i}-2^n\tag{6}\\
\end{align*}

Comment:

*

*In (2) we replace $j\rightarrow n-j$

*In (3) we shift the index $i$ to start from $0$

*In (4) we use $\binom{n}{k}=\binom{n}{n-k}$ and we replace $i\rightarrow j-1-i$. We also note that $j$ starts with $j=1$ due to the upper index of $i$ equal to $j-1$.

*In (5) we shift the index $j$ by one.

*In (6) we add $j=n$ to the double sum and subtract $2^n$ accordingly.

We see, the double sum with the upper triangle as index range can be transformed to the double sum with the lower triangle as index range. Putting all together we obtain
\begin{align*}
  \sum_{j=0}^n&\sum_{i=0}^j\binom{n+1}{j+1}\binom{n}{i}+
  \sum_{j=0}^n\sum_{i=j+1}^n\binom{n+1}{j+1}\binom{n}{i}\\
  &=2\sum_{j=0}^n\sum_{i=0}^j\binom{n+1}{j+1}\binom{n}{i}-2^n
  \end{align*}
We obtain with (1)
\begin{align*}
  2\sum_{j=0}^n\sum_{i=0}^j\binom{n+1}{j+1}\binom{n}{i}-2^n&=2\cdot 4^n-2^n\\
  \end{align*}
resp.
\begin{align*}
  \sum_{j=0}^n\sum_{i=0}^j\binom{n+1}{j+1}\binom{n}{i}&=4^n\\
  \end{align*}
and the claim follows.

A: Define $$F_n:=\sum_{j=0}^n\sum_{i=0}^j\binom {n+1}{j+1}\binom ni$$where $n\ge0.$ Then keeping in mind the symmetry of binomial coefficients,\begin{align}F_n
&=\sum_{j=0}^n\sum_{i=0}^j \left[\binom nj+\binom n{j+1}\right]\binom ni\\
&=\sum_{j=0}^n\sum_{i=0}^j \binom n{j}\binom ni + \sum_{j=0}^n\sum_{i=0}^{j+1} \binom n{j+1}\binom ni-\sum_{j=0}^n\binom n{j+1}^2\\
&=\sum_{j=0}^n\sum_{i=0}^j \binom n{j}\binom ni + \sum_{j=1}^n\sum_{i=0}^{j} \binom n{j}\binom ni-\sum_{j=1}^n\binom n{j}^2\\
&=2\sum_{j=0}^n\sum_{i=0}^j \binom n{j}\binom ni -\sum_{j=0}^n\binom n{j}^2\\
&=\left(\sum_{i=0}^n \binom ni\right)^2\\\\
&=2^{2n}
\end{align}
Q.E.D.


text:
Q: Create specific embed discord with a class I want to create my discord embed with a class named embed because the embed lines takes a lot of space in my code and I want to optimize it. Thank you for reading me.
My discord file
@bot.command()
async def test(ctx): # Commande de test pour vérifier que le bot est bien en Etat de répondre
    '''Commande inutile pour le moment'''
    embed_test = embed.EMBED("title", "description", "!nom_fonction",
    "https://www.supersoluce.com/sites/default/files/styles/picto_soluce/interrogation.png")
    embed_test.create()
    embed_test.add_field("Test1", "Value1")
    embed_test.add_field("Test2", "Value2")
    await ctx.send(embed=embed_test)

My embed.py file
from urllib.parse import urlsplit, parse_qs
import discord

class EMBED:
    def __init__(self, title, description, nom_fonction=None, logo=None, color=0x1f6e9e):
        self.embed_title = title
        self.embed_description = description
        self.embed_nom_fonction = nom_fonction
        self.embed_logo = logo
        self.embed_color = color
        self.embed = discord.Embed(title= self.embed_title, url= "https://myges.fr", description= self.embed_description, color= self.embed_color)

    def create(self):
        self.embed.set_author(name=f"ESGI | {self.embed_nom_fonction}", icon_url= self.embed_logo)
        self.embed.set_thumbnail(url="https://www.sciences-u-lyon.fr/images/2020/03/myges.png")
        self.embed.set_footer(text="Made by DAVE")

    def add_field(self, name, value, inline=True):
        self.embed.add_field(name=name, value=value, inline=inline)

Error message:
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\rmassiet\Desktop\ESGI bot\ESGI_BOT_DISCORD\main.py", line 70, in test
    await ctx.send(embed=embed_test)
  File "C:\Python310\lib\site-packages\discord\abc.py", line 1017, in send
    embed = embed.to_dict()
AttributeError: 'EMBED' object has no attribute 'to_dict'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\rmassiet\Desktop\ESGI bot\ESGI_BOT_DISCORD\main.py", line 113, in on_command_error
    raise error
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'EMBED' object has no attribute 'to_dict'

A: Internally discord.py sends the embed as JSON data (represented as a dict in python). You can create your own to_dict method to fix the issue
class EMBED:
    ...

    def to_dict(self):
        return self.embed.to_dict()


text:
Q: In JS of LWC, line after forEach statement does not execute I have below Javascript function in lwc
apexJobInfoData;
@track isBatch;
getData({ error, data }) {
    if (error) {
        // TODO: handle error
    } else if (data) {
        this.jobId = getFieldValue(data, JOB_ID);
        getAllApexJobInfo({ ApexJobId: this.jobId})
        .then(result => {
            this.apexJobInfoData = result.JobInfo.length===0?null:result.JobInfo;
            this.error = undefined;

            if(apexJobInfoData!=null){
                apexJobInfoData.forEach((element) => {
                        if(element.JobType === 'BatchApex'){
                            this.isBatch = true;
                        }
                  })
            }
            alert('Error Calling Alert Here');  // This line does not execute
        })
        .catch(error => {
            this.message = undefined;
            this.error = error;
        });
    }

I am not sure what's happening but after there is something wrong with below piece of code. After this nothing gets executed.
        if(apexJobInfoData!=null){
            console.log('Enters here');
            apexJobInfoData.forEach((element) => {
                 console.log('Doesn't enter here');
              })
        }

What am I missing here.

A: Looks to me like you are missing "this" references:
    .then(result => {
        this.apexJobInfoData = result.JobInfo.length===0?null:result.JobInfo;
        this.error = undefined;

        if(this.apexJobInfoData!=null){ // HERE
            this.apexJobInfoData.forEach((element) => { // HERE TOO
                    if(element.JobType === 'BatchApex'){
                        this.isBatch = true;
                    }
              })
        }


text:
Q: Other than others, Hilios countdown timer Im wondering, if there is such a way, to edit Hilios countdown timer described as below:
I've got a function, which works as it should, to counts down time from date (I want to mark, that I do have several dates in single view, where timer is used, so I had to go with each function):
$('[data-countdown]').each(function() {
    var $this = $(this);
    var finalDate = $(this).data('countdown');
    $this.countdown(finalDate, function(event) {
        $this.html(event.strftime('%D days %H:%M:%S'));
    });
});

And here comes the problem. As this script works "staticly" - what I mean by static - is that it get's the date from html and passes it into the script as the script is loaded.
My application works dynamically, so also the date's are changed dynamically.
So the question is: Is there such a way to edit this script, to work with dynamic data - when some data is updated on the website, it also updates that data in the countdown timer.
Best regards! PS.

A: Please check out MutationObserver.

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = {
  attributes: true,
  attributeFilter: ['data-timer'],
  attributeOldValue: true,
};

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
  for (var mutation of mutationsList) {
    console.log('CHANGED', mutation.oldValue);
  }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
//observer.disconnect();

hello

<button onclick="document.getElementById('some-id').setAttribute('data-timer', +new Date())">change</button>


text:
Q: UnicodeDecodeError when I set recursive=True in FilePathField in django The error happened when I add record in admin. My model is like

class THMusic(models.Model):
     originmusic = models.ForeignKey(Originalmusic)
     name = models.CharField(max_length=100)
     audiofile = models.FilePathField(path=os.path.dirname(os.path.abspath(__file__))+'/resource', recursive=True)
     team = models.CharField(max_length=50)
     album = models.CharField(max_length=50)
class THMusicAdmin(admin.ModelAdmin):
     list_display = ('name', 'originmusic', )

But I get UnicodeDecodeError:

UnicodeDecodeError at /admin/thmusic/thmusic/add/

'ascii' codec can't decode byte 0xe3 in position 54: ordinal not in range(128)

Request Method:     GET
Request URL:    http://127.0.0.1:8006/admin/thmusic/thmusic/add/
Django Version:     1.6.5
Exception Type:     UnicodeDecodeError
Exception Value:

'ascii' codec can't decode byte 0xe3 in position 54: ordinal not in range(128)

Exception Location:     /usr/local/lib/python2.7/dist-packages/django/forms/fields.py in __init__, line 1057
Python Executable:  /usr/bin/python2.7
Python Version:     2.7.6
Python Path:

['/home/hyzhappy/djangoprojects/myblog',
 '/usr/local/lib/python2.7/dist-packages/simplejson-3.6.3-py2.7-linux-i686.egg',
 '/home/hyzhappy/djangoprojects/myblog',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-i386-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/local/lib/python2.7/dist-packages/PIL',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gst-0.10',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']

If I delete "recursice=True" in FilePathField, it will go well. But it's not my expectation
More detail

Unicode error hint
      The string that could not be encoded/decoded was: urce/������
      UnicodeDecodeError('ascii', '/home/hyzhappy/djangoprojects/myblog/thmusic/resource/\xe3\x83\x97\xe3\x83\xac\xe3\x82\xa4\xe3\x83\xa4\xe3\x83\xbc\xe3\x82\xba\xe3\x82\xb9\xe3\x82\xb3\xe3\x82\xa2.mp3', 54, 55, 'ordinal not in range(128)')

A: Probably not the right answer, but you can check this as a possible cause.
Sometimes in Django (I had the same case with tastypie), the UnicodeDecodeError occurs because of an initial unrelated error which tries to display but can not because of weird character.
In my case, it was because I put French accents in my code comments (not ascii). This usually does not create errors, but when there is actually an error somewhere and Django tries to display this error in the debug mode, it can not because of the non ascii chars and raises a UnicodeDecodeError instead of raising the initial error.
Just try to remove any suspicious character in your code (if there is any), and check again to see if the error is still the same.

A: Under the hood, FilePathField uses os.walk/os.listdir to find the files. These functions have two "modes" of operation in python: byte string and unicode. The mode is selected by the type of path given, i.e. if you feed it an unicode string, the resulting file list will be unicode, otherwise it will be a byte string.
So, to fix this problem, just feed a unicode path to the FilePathField, like this (note the u at the beginning of u'/resource'):
audiofile = models.FilePathField(path=os.path.dirname(os.path.abspath(__file__))+u'/resource', recursive=True)


text:
Q: Стэковая память в С++ Как уменьшить размер массива на 1 элемент в функции pop()? Можно через вектор, было бы проще. Но надо поменять размер массива(как-то)
#include<iostream>

template<typename T>
struct stack {
 private:
  T* array = new int[1];
 public:

  stack push(T n) {
   array[sizeof(array)] = n;
   array = (int *) realloc (array,sizeof(int) * sizeof(array));
  }

  stack pop() {
   array[sizeof(array)] =
  }

  T top() {
   return array[sizeof(array)];
  }

  bool empty() {
   if(sizeof(array) == 1) return true;
   else return false;
  }
};

int main() {
 stack<int> abc;
 abc.push(5);
 abc.push(10);
 printf("%d\n", abc.top());
 printf("%s\n", abc.empty() == 0 ? "False" : "True");
 abc.pop(); //5
 printf("%d\n", abc.top());
}

A: Для стека вам определённо нужно использовать структуру односвязного списка
template<class T>
class stack_element {
public:
    T _value;
    stack_element<T>* _prev;
    stack_element(T& value, stack_element<T>* prev) : _value(value), _prev(prev) {}
};

template<class T>
class stack {
private:
    stack_element<T>* _top = nullptr;
public:
    stack<T>& push(T& value) {
        _top = new stack_element<T>(value, _top);
        return *this;
    }
    stack<T>& pop() {
        stack_element<T>* del_elem = _top;
        _top = _top._prev;
        delete del_elem;
        return *this;
    }
    T& top() {
        if (!_top){
            throw std::exception("top is nullptr");
        }
        return _top._value;
    }
    bool empty() { return !_top;}
};

По хорошему нужно ещё учесть rvalue и ещё много чего, но на первое время достаточно


text:
Q: Proof that $\lim \sup_n (a_n + b_n) \in \mathbb{R}$ when $\lim \sup_n a_n \in \mathbb{R}$, $\lim \sup_n b_n \in \mathbb{R}$ I'm stuck in the middle of solving the following question.
Say $\lim \sup_n a_n = \alpha \in \mathbb{R}$, $\lim \sup_n b_n = \beta \in \mathbb{R}$. Then can we say the following?
$$
\lim \sup_n (a_n + b_n) \in \mathbb{R}
$$
My attempt : define $x_n = \sup \{a_k : k \ge n \} $, $y_n = \sup \{b_k : k \ge n \} $. Then by the assumption, both $\{x_n : n \in \mathbb{N}\}$ and $\{y_n : n \in \mathbb{N}\}$ are bounded below.
Define $z_n = \sup \{a_k + b_k : k \ge n \}$. I think the fact I can use now is $z_n \le x_n + y_n$. But I find that this does not exclude the possibility of $\{z_n : n \in \mathbb{N}\}$ being NOT bounded below, i.e. $\lim_n z_n = -\infty$.
Is there anyone to help me proceed my proof? Or, can someone give a counter-example?

A: That's false.
Let $a_n = -n$ for even $n$, and $0$ otherwise.
Let $b_n = -n$ for odd $n$, and $0$ otherwise.
Then:
$$\limsup_n a_n = 0,\,\limsup_n b_n = 0,\,\limsup_n (a_n+b_n) = -\infty$$


text:
Q: importing external libraries ng2-tag-input into Angular 2 I'm attempting to use the ng2-tag-input library in my angular 2 application. I've run:
npm install ng2-tag-input --save

I verified that the file installed in the node_modules folder
I added the import statement to app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { TagInputModule } from 'ng2-tag-input';

I added it to imports section of the @NgModule
@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        TagInputModule,

At this point when I start the application I get an error:
GET http://localhost:3000/ng2-tag-input 404 (Not Found)
scheduleTask @ zone.js:1382
ZoneDelegate.scheduleTask @ zone.js:245
Zone.scheduleMacroTask @ zone.js:171
(anonymous) @ zone.js:1405
send @ VM104:3
fetchTextFromURL @ system.src.js:1156
(anonymous) @ system.src.js:1739
ZoneAwarePromise @ zone.js:518
(anonymous) @ system.src.js:1738
(anonymous) @ system.src.js:2764
(anonymous) @ system.src.js:3338
(anonymous) @ system.src.js:3605
(anonymous) @ system.src.js:3990
(anonymous) @ system.src.js:4453
(anonymous) @ system.src.js:4705
(anonymous) @ system.src.js:408
ZoneDelegate.invoke @ zone.js:232
Zone.run @ zone.js:114
(anonymous) @ zone.js:502
ZoneDelegate.invokeTask @ zone.js:265
Zone.runTask @ zone.js:154
drainMicroTaskQueue @ zone.js:401
ZoneTask.invoke @ zone.js:339
VM111:29 Error: Error: XHR error (404 Not Found) loading http://localhost:3000/ng2-tag-input
        at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:698:29)
        at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:265:35)
        at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:154:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:335:33)
    Error loading http://localhost:3000/ng2-tag-input as "ng2-tag-input" from http://localhost:3000/app/app.module.js

What am I doing wrong? Thanks in advance.


text:
Q: Assign value to an hidden text input with JS i'm a newbie of JavaScript.
I have that :
HTML:
<form>
<t:inputFileUpload required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />
<h:commandButton class="btn btn-primary" value="Upload"
            action="#{controller.upload}" />
</form>

javascript:
<script>
function uploadOnChange() {

document.getElementById('upload').onchange = name;

var filename = name;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
    filename = filename.substring(lastIndex + 1);

document.getElementById('filename').value = filename;
}
</script>

All I want to do is get through a inputFileUpload, to browse my directory, the filename that i've selected, and pass this name as a string to jsf controller.
Does anyone can help me?
EDIT :
If I add to my form enctype="multipart/form-data seems that the controller method "upload" does nothing.

A: Assuming <t:inputFileUpload> has a value attribute, I'd change the code to something like this:

function uploadOnChange() {
  var filename = document.getElementById('upload').value;
  var lastIndex = filename.lastIndexOf("\\");
  if (lastIndex >= 0) {
    filename = filename.substring(lastIndex + 1);
    document.getElementById('filename').value = filename;
  }
  console.log('Value hidden input: ' + document.getElementById('filename').value);
}
<input type="file" required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />


text:
Q: Angular 2 RC6 - Cross origin requests error After migrating to RC6, I started getting a bunch of errors when initialising my application.
At first, I was hitting the traceur not found error, which I've solved.
I've added the correct packages to package.json and pointed system.config.js to work with the UMD files.
However, now I get a bunch of other errors like the one bellow (more precisely, I get 121 errors.

zone.js:1241 XMLHttpRequest cannot load npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.scheduleTask
(...)
33system.src.js:373 Assertion failed: loading or loaded

What's the deal with this? How can I solve it?
I've explicitly set my "server" requests (on the service classes) to explicitly define the Headers but I'm still hitting this issue.
Anyone else faced the same problem?
EDIT
Adding system.config.js and package.json for clarification
System.config.js
 (function(global) {
    System.config({
    paths: {
      'npm:': 'node_modules'
    },
    // map tells the System loader where to look for things
    map: {
      'app': 'www/build', // 'dist',

      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',

      // angular testing umd bundles
      '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
      '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
      '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
      '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
      '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
      '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
      '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',

      'rxjs': 'npm:rxjs',
      'primeng': 'npm:primeng',
      'lodash': 'npm:lodash',
      'angular2-jwt': 'npm:angular2-jwt/angular2-jwt.js',

      'routes': 'app/routes',
      'services': 'app/services'
    },

    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {main: 'app.js', defaultExtension: 'js'},
      rxjs: {defaultExtension: 'js'},
      primeng: {defaultExtension: 'js'},
      lodash: {main: 'index.js', defaultExtension: 'js'},
      'angular2-jwt': {defaultExtension: 'js'}
    }
    })
    })(this);

package.json
    {
     "name": "my-admin",
     "version": "0.0.1",
     "description": "Admin UI",
     "private": true,
     "main": "",
     "scripts": {
       "postinstall": "npm run typings install",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "lite": "lite-server",
        "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
        "typings": "typings"
     },
    "dependencies": {
      "@angular/common": "2.0.0-rc.6",
      "@angular/compiler": "2.0.0-rc.6",
      "@angular/core": "2.0.0-rc.6",
      "@angular/forms": "2.0.0-rc.6",
      "@angular/http": "2.0.0-rc.6",
      "@angular/platform-browser": "2.0.0-rc.6",
      "@angular/platform-browser-dynamic": "2.0.0-rc.6",
      "@angular/router": "3.0.0-rc.2",
      "angular-cli": "^1.0.0-beta.10",
      "angular2-jwt": "^0.1.22",
      "chart.js": "^2.2.1",
      "core-js": "^2.4.1",
      "lodash": "^4.15.0",
      "ng2-translate": "^2.4.2",
      "primeng": "^1.0.0-beta.15",
      "primeui": "^4.1.12",
      "reflect-metadata": "^0.1.3",
      "rxjs": "5.0.0-beta.11",
      "systemjs": "^0.19.27",
      "timsort": "^0.3.0",
      "tslint": "^3.13.0",
      "zone.js": "^0.6.21",
    "es6-shim": "^0.35.1"
    },
    "devDependencies": {
      "concurrently": "^2.0.0",
      "del": "^2.2.0",
      "eslint": "^3.1.0",
      "eslint-config-google": "^0.6.0",
      "fs": "0.0.2",
      "gulp": "^3.9.1",
      "gulp-autoprefixer": "^3.1.1",
      "gulp-concat": "^2.6.0",
      "gulp-debug": "^2.1.2",
      "gulp-insert": "^0.5.0",
      "gulp-minify-css": "^1.2.4",
      "gulp-sass": "^2.3.2",
      "gulp-watch": "4.3.5",
      "lite-server": "^2.2.2",
      "http-server": "^0.9.0",
      "run-sequence": "1.1.5",
      "typescript": "^1.8.10",
      "typings": "^1.0.4"
     },
     "repository": {
      "type": "git",
    "url": "<url>"
  },
  "author": "Myself",
  "license": "ISC",
  "homepage": "<url>#readme"
}


text:
Q: Alternatives to TextEdit? I use TextEdit on the mac for nearly everything I do, making notes, writing letters, etc.
I'm interested to find out what you use (if you use an alternative)?
I've found that "competitors" like BBEdit and TextMate are just too overcomplicated for what I need.

A: aquamacs - Emacs for Mac OS X

A: Vim, multi-platform, the same everywhere. No new suprises when you go somewhere.

A: I'd recommend Smultron. As a plain text editor it's pretty good for replacing TextEdit. Offers a good replacement if you're not looking for anything fancy.

A: While it's command-line, pico is another option for those non familiar with vi/emacs.

A: If you want a simple word processor, try Bean. It's lightweight, Mac-like, and, because it is written using Apple's Cocoa framework, it offer's Cocoa's good stuff -- dictionary, word completion and more. It's open source (under the GNU General Public License), free of charge. From its home page:

Why use Bean?
Bean is lean, fast and uncluttered.

*

*If you get depressed at the thought of firing up MS Word or OpenOffice,
  try Bean.

*If you use Text Edit but have to jump through hoops just to get a word
  count, try Bean.

*If you desire a simple, beautiful writing environment, try Bean. . . .

  Bean doesn't . . .
  do footnotes, pre-defined text styles, floating graphics (but it does do
  in-line graphics).

A: Once you get to know some of the features in TextMate, it definitely has some time savers! I used it for note taking all last year, and it worked like a charm.

A: jEdit is a great text editor for pretty much anything.

A: If you're using the text editor strictly for notes, letters, and other person to person correspondence, then editors such as
Apple's Pages
Microsoft Word
PageHand
OpenOffice
Mellel
Nisus
If you're looking more for plain text editor for programming
SubEthaEdit
TextWranger

A: Between TextEdit, Xcode, nano and Pages, I have everything I need. It works for me.

A: Scrivener for plain text writing in full screen mode is brilliant, I have a project for working text and just add new sections to it. Just you and your words. The fact that it supports markdown (which SuperUser also uses for text entry, markdown rocks!) means you can write intuitively in plain text yet formatting comes for free, which is great! Scrivener UI gets out of your way, but when you need features (snapshots of a text for example, great for quick versioning of a letter), is there.
Textmate for everything code. There is nothing complicated about TM, it has such a minimalist UI often people wonder what is special about it! ;-)
myText is also not bad for a cheap full-screen editor (a WriteRoom clone better than the original). It allows managing all your text documents and an easy search through them. Brilliantly it uses proper tagging and works well with spotlight.

A: TextWrangler
I use it for all my note taking stuff, I find it fast and responsive. It also will intergrate nicely with a lot of other applications, such as Cyberduck which I use for FTP.
It's made by the same people who make BBEdit, but it's also a fair bit less complicated.
SubEthaEdit is probably a bit over complicated for what you're looking for.
myTexts is an application that I've been meaning to try. If other applications are too complicated, this just might do the trick - it looks promising!

A: Stickies!

Checkout 10 tips for Stickies for improving your Stickies experiance. My favorite is the very last:

Create a Sticky note from selection
Due to the Services menu in Mac OS X, you have access to Stickies whatever application you are in. Simply select any block of text anywhere and hit Command-Shift-Y to create a Sticky note with that selection.

I use them quite a lot, especially for jotting down quick, temporary notes for school:

That screenshot is after I deleted a couple and trimmed down the content in a couple others.

A: Maybe what you are looking for is a note keeper/organizer where the notes are easily searchable.   Something like Circus Ponies' Notebook or Voodoo Pad.  This way you don't have to save a new document each time you want to add a note, web link, image, or sound clip.  I leave VoodooPad Pro running all the time.
Each have their strong points.
Notebook is a more complete experience, formatting numberd lists and sublists is easier. As well as more eye candy, stickies and post-it flags, and animations.  Notebook also provides a service to clip from within any application and add it to your Notebook document.
Voodoo Pad Lite's price is right and provides most of the functionality of the regular version. VoodooPad has a higher geek factor, you can embed scripts in real languages (Python, Lua) and execute them from within Voodoo Pad.  The Pro version includes whole document encryption and a built it web server.
Both have demos available of the full version so give them a spin.


text:
Q: ASP.NET - running a bat script on another machine I would like to run a bat script on one of the machines on the domain, from my asp.net application. Machine with the batch script is a temporary storage machine, and script synchronizes it with the permanent storage machine. So, what is the optimal way of doing this?
The thing I tried is to use PsExec to run a script on the remote machine. I create  a process that makes a PsExec call, and it actually does it's job pretty well. However, since the ASP.NET worker thread runs under ASP.NET account that has restricted privileges, I must hard-code my domain user credentials in PsExec call, and that's something I do not like doing.
Is there a way to overcome this problem, or maybe some other approach that I could try?
Thanks...

A: You can use the <identity impersonate="true" /> setting in your Web.config to have the application run under the IUSR, or you can set a username/password on the identity tag to an account you'd like to use to run the BAT file.
I had previously found some details on Impersonate over at: http://www.aspdev.org/articles/web.config/
But I'm sure a quick web search will find you even more info on Impersonate.

A: The answer above doesn't work. New processes will be spawned by default under the ASP.NET account.
see http://support.microsoft.com/kb/889251.
"To spawn a process that runs under the context of the impersonated user, you cannot use the System.Diagnostics.Process.Start method. This is because in ASP.NET, impersonation is performed at the thread level and not at the process level. Therefore, any process that you spawn from ASP.NET will run under the context of the ASP.NET worker process and not under the impersonated context."


text:
Q: Matching codons using lists, dictionaries and loops This is one of the more difficult problems I have faced so far so excuse my for not providing a substantial attempt at doing it.
I want a program that prints matching codons in the format:
AAA : TTT
GGG : CCC
TTT : AAA
CCC : GGG
    .
    .
    .

Here is what I did:
pairs = {'A':'T','C':'G','T':'A','G':'C'}
codonsA = ['AAG', 'TAC', 'CGG', 'GAT', 'TTG', 'GTG', 'CAT', 'GGC', 'ATT', 'TCT']
codonsB = ['TAA', 'CTA', 'AAC', 'TTC', 'AGA', 'CAC', 'CCG', 'ATG', 'GCC', 'GTA']
for A in codonsA:
    print A + ' :',
    for B in codonsB:
        print B,
    print

#OUTPUT:

AAG : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
TAC : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
CGG : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
GAT : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
TTG : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
GTG : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
CAT : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
GGC : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
ATT : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA
TCT : TAA CTA AAC TTC AGA CAC CCG ATG GCC GTA

What I need to do now is to get rid off 9 codons from B from each row on the right of the colon and leave only the one codon on the right that matches the codon from A on the left. How do I do that?

A: You don't even need that codonsB list.  A codon maps onto its anticodon complement 1:1.
def anticodon(codon):
    """returns the anticodon complement for a given codon"""
    return ''.join(pairs[c] for c in codon)

anticodon('AAG')
Out[5]: 'TTC'

You're free to check if each element in codonsA has an anticodon in codonsB, if you need to make that check.
all(anticodon(c) in codonsB for c in codonsA)
Out[6]: True

And the output I think you were originally looking for:
for codon in codonsA:
    print '{} : {}'.format(codon,anticodon(codon))

AAG : TTC
TAC : ATG
CGG : GCC
GAT : CTA
TTG : AAC
GTG : CAC
CAT : GTA
GGC : CCG
ATT : TAA
TCT : AGA