text:
Q: How to get a partition back after choosing erase disk and install, but stopping the process there My laptop is a Dell 7567 with no SSD, Windows 10, SSHD 1tb
I have created a volume to install Ubuntu 16.04.5 (30gb). But I made a mistake when choosing to erase the disk. I went back immediately, so please notice that no installing process ran.
However, the list of partitions of my laptop has changed, and Windows lost its partitions. So I can't run Ubuntu or Windows, Using Try Ubuntu right now.
Originally, there was a C drive for Windows, D drive for data and 30gb unallocated for Ubuntu.
I know when the option Erases the disk and install Ubuntu is checked, it will collect all the partitions of hard disk. But I stopped before the install process. Is there any way to get the partitions back for Windows, because I need the data? I hope it was not wiped.
now the partitions looks like this


text:
Q: Required WebGL extensions detection I am working on a WebGL (using ThreeJs) application that, obviously, shows 3D models, and we are using some effects (shaders), looking to make a test to know whether the user can run the app or not, I find a way to retrieve a list of the supported plugins in the used browser.
The Question:
the problem that I am facing is rather to know what are the required plugins for my application, is there a way to automatically detect them?

More details:
for further details I would specify an example of what I need:

*

*In my MacBook Pro under Mac OSX Maverix, the application is working fine

*Testing the application on my Lenovo Laptop, under Windows 7, then Windows 8, the application is not working, and the problem is cause by the Bokeh2 Shader.

Examining the list of supported WebGL extensions I've found that there are some extension that are missing in Lenovo compared to Mac, so how can I tell which are the required extension that if missing will break the WebGL app.
This is a list of the extension I have in both, mac and lenovo.
In my Mac:

ANGLE_instanced_arrays
WEBKIT_EXT_texture_filter_anisotropic
OES_element_index_uint
OES_standard_derivatives
OES_texture_float
OES_texture_float_linear
OES_texture_half_float
OES_texture_half_float_linear
OES_vertex_array_object
WEBKIT_WEBGL_compressed_texture_s3tc
WEBKIT_WEBGL_depth_texture
WEBGL_draw_buffers
WEBGL_lose_context
WEBGL_debug_renderer_info

In my Lenovo:

ANGLE_instanced_arrays
WEBKIT_EXT_texture_filter_anisotropic
OES_element_index_uint
OES_standard_derivatives
OES_texture_float
OES_texture_half_float
OES_texture_half_float_linear
OES_vertex_array_object
WEBKIT_WEBGL_compressed_texture_s3tc
WEBGL_lose_context
WEBGL_debug_renderer_info

The missing ones in Lenovo:

OES_texture_float_linear
WEBKIT_WEBGL_depth_texture
WEBGL_draw_buffers

A: You can check for an extension by asking for it
var ext = gl.getExtension("OES_texture_float_linear");
If (!ext) {
  alert("extension does not exist");
}

For three.js you can use
var gl = renderer.getContext();

To get the WebGLRenderingContext
In your case if the extension does not exist consider not using the bokeh2 shader
Otherwise, it's up to the app/framework/code to tell you which extensions are needed. I can think of 3 ways off the top of my head

*

*The ideal way would be for the app to specific in the docs as in Bokek2 needs extensions X, Y, and Z.

*The next best way would be to just look through the code and see what it's doing.

*One other way would be to override getExtension and then (1) print out which extensions are being checked for and (2) return null for certain extensions and see when the code fails.
I'd really suggest #2 above but for #3 you could do this
(function() {

  var originalGetExtensionFunction = WebGLRenderingContext.prototype.getExtension;

  // start with this array empty. Once you know which extensions
  // the app is requesting you can then selectively add them here
  // to figure out which ones are required.
  var extensionToReject = [
    "OES_texture_float",
    "OES_texture_float_linear",
  ];

  WebGLRenderingContext.prototype.getExtension = function() {
    var name = arguments[0];
    console.log("app requested extension: " + name);
    if (extensionToReject.indexOf(name) >= 0) {
      console.log("rejected extension: " + name);
      return null;
    }
    var ext = originalGetExtensionFunction.apply(this, arguments);
    console.log("extension " + name + " " + (ext ? "found" : "not found"));
    return ext;
  };

}());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lua - Count the no. of references to a table The Lua docs say

When a program has no references to a table left, Lua memory
  management will eventually delete the table and reuse its memory.

My question is :  Is it possible to count the no of references to a particular table during runtime?

A: You can find all references to a Lua value using the debug library. See these messages:

*

*http://lua-users.org/lists/lua-l/2012-03/msg00479.html

*http://lua-users.org/lists/lua-l/2012-04/msg00758.html
The luatraverse library found in the below link solves this nicely!
http://code.matthewwild.co.uk/luatraverse/summary


text:
Q: tmhOAuth failed to validate oauth signature and token I'm trying to use The Matt Harris's oAuth php library to get user access tokens from Twitter users on my app, but I keep getting the error "Failed to validate oauth signature and token".
Specifically, I'm trying to use a slightly modified version of his OAuth flow tutorial to get their tokens and store them in my database rather than the session. https://github.com/themattharris/tmhOAuth/blob/master/examples/oauth_flow.php
The error always occurs in the request token function here.
function request_token($tmhOAuth) {
    $code = $tmhOAuth->request(
       'POST',
       $tmhOAuth->url('oauth/request_token', ''),
       array(
           'oauth_callback' => tmhUtilities::php_self()
       )
    );

    if ($code == 200) {
        $_SESSION['oauth'] = $tmhOAuth->extract_params($tmhOAuth->response['response']);
       authorize($tmhOAuth);
    } else {
       outputError($tmhOAuth);
    }
}

I've already checked the server time, and I know it's within 5 seconds of GMT. One of the Twitter developers said the time should be within about 5 minutes of their servers, so I should be fine. https://dev.twitter.com/discussions/1043
I've also checked that the cacert.pem file is in the same place as the rest of the files, right where CURL expects it to be, and I have the 'use_ssl' and 'curl_ssl_verifypeer' options turned off, since my site does not currently have an SSL certificate set up.
Here is the returned response object:
["response"]=> array(6) {
        ["headers"]=> array(16) {
            ["date"]=> string(29) "Sat, 25 Aug 2012 16:38:24 GMT"
            ["status"]=> string(16) "401 Unauthorized"
            ["x_frame_options"]=> string(10) "SAMEORIGIN"
            ["x_mid"]=> string(40) "4147a367997b7a5221cbcd8446652b1ebc00230d"
            ["last_modified"]=> string(29) "Sat, 25 Aug 2012 16:38:24 GMT"
            ["content_type"]=> string(24) "text/html; charset=utf-8"
            ["expires"]=> string(29) "Tue, 31 Mar 1981 05:00:00 GMT"
            ["cache_control"]=> string(62) "no-cache, no-store, must-revalidate, pre-check=0, post-check=0"
            ["x_runtime"]=> string(7) "0.01766"
            ["pragma"]=> string(8) "no-cache"
            ["x_transaction"]=> string(16) "b8ffe07df233ba05"
            ["set_cookie"]=> string(265) "_twitter_sess=ginormous session id; domain=.twitter.com; path=/; HttpOnly"
            ["vary"]=> string(15) "Accept-Encoding"
            ["content_encoding"]=> string(4) "gzip"
            ["content_length"]=> string(2) "62"
            ["server"]=> string(3) "tfe"
        }
        ["code"]=> int(401)
        ["response"]=> string(44) "Failed to validate oauth signature and token"
        ["info"]=> array(23) {
            ["url"]=> string(42) "http://api.twitter.com/oauth/request_token"
            ["content_type"]=> string(24) "text/html; charset=utf-8"
            ["http_code"]=> int(401) ["header_size"]=> int(1030)
            ["request_size"]=> int(498) ["filetime"]=> int(-1)
            ["ssl_verify_result"]=> int(0)
            ["redirect_count"]=> int(0)
            ["total_time"]=> float(0.265656)
            ["namelookup_time"]=> float(0.062211)
            ["connect_time"]=> float(0.139025)
            ["pretransfer_time"]=> float(0.139028)
            ["size_upload"]=> float(0)
            ["size_download"]=> float(62)
            ["speed_download"]=> float(233)
            ["speed_upload"]=> float(0)
            ["download_content_length"]=> float(62)
            ["upload_content_length"]=> float(-1)
            ["starttransfer_time"]=> float(0.265504)
            ["redirect_time"]=> float(0)
            ["certinfo"]=> array(0) { }
            ["redirect_url"]=> string(0) ""
            ["request_header"]=> string(498) "POST /oauth/request_token HTTP/1.1 User-Agent: tmhOAuth 0.621-SSL - //github.com/themattharris/tmhOAuth Host: api.twitter.com Accept: */* Accept-Encoding: deflate, gzip Authorization: OAuth oauth_callback="http%3A%2F%2Fcompleteset.us%2Fsettings%2Ftwitterlink", oauth_consumer_key="consumer_key", oauth_nonce="nonce", oauth_signature="sig", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1345912704", oauth_version="1.0" "
        }
        ["error"]=> string(0) ""
        ["errno"]=> int(0)
    }

I have noticed that before I set 'use_ssl' to false the headers array in the response wasn't there. I'm not sure what that means or if it helps, but I figured I might as well throw it out there.
I also have the entire rest of the tmhOAuth object dumped if you need any of the other sections.


text:
Q: View width is not equal to cell width inseide uitable? I am trying to add a view inside a UITableCell.It works fine for all the devices but on iPad the width of view is not equal to cell width.The width of view is half of the width of cell.Please tell me what do here.
Constraints are:

A: please select width and height (any,any) in storyboard.It may be helpful to you.

A: You Can use constrain
First select view which you put on cell and give constrain from 4 side
like below in image
give it top,bottom,left,right = 0


text:
Q: Multi store view confusion, page 404's redirects and Magento store codes I have set up several store views(for different languages), all under the same website and store.
The languages appear nicely, and I can switch between them. I have created several categories and started to localize them. All was going nicely.
The way I have set up the categories was like this(example):
/women (name:"Women", slug:"women")
-->shoes (name "Shoes", slug: "shoes")
And one of it's translations:
/zhen (name:"Zhen", slug:"zhen")
-->obuv (name:"Obuv", slug:"obuv")
I could see my products, categories appear on the website and I could switch between languages using the language switcher.
Now, the problems arose when I noticed that I could only get to see the pages in other languages if I used the language switcher. If I copy pasted a mysite.com/zhen/obuv into an incognito window, it would show me a 404. So in other words, If I sent the link to a person, he would also get the 404. So the only way to see the page in other languages was to use the language switcher(which presumably wrote a cookie to the browser), which would allow to see the localized category/page of the website.
I have checked URL rewrites in the Magento settings, they do look correct, i.e. both of those slugs/url are pointing to the same category(target path).
I have tried everything, emptying the URL rewrite table. Re-indexing, clearing cache, checking and re-checking all setting for store views/categories etc.
Then I've tried to set the "Add Store Code to Urls" to Yes. Which resolved all the problems, but also added a mysite.com**/en/** store codes to every page/store. Now it works more or less ok.
My questions are:
1. Where the URLs not resolving because it is not intended to be used that way(in the case of multi store)? (All things should have the same slug in case that I'm not suing store  codes?)
2. Is it imperative to use store codes (like /en/) when trying to run a multi store view website?
Am I missing something here?

A: To get around this problem, you could consider using another URL for the second store view and then explicitly set that store ID -> then it would work.
Let's assume you have www.store.com
Then use for example www.store.com/de/ for the German store view (i.e. set this as the base URL for that store view in your backend).
In the index.php (or better using .htaccess logic) you should then detect that whenever there is /de/ in your URL, you set the store ID to your second store view.
That way, the URL of the translated store is uniquely detectable and everything will work out while you still keep the original URL for your main store.

A: There is no best practice it's more of an SEO question quoted from seomoz:

"If you're targeting a specific country, think about using a ccTLD.
  But, if you are focusing on language targeting only, a ccTLD probably
  isn't your best choice as they're meant for targeting a specific
  geographic area and not specifically the language spoken there. In
  these cases, you'll likely want to use a different
  internationalization technique such as using hreflang, subfolders, or
  subdomains in combination with or instead of using a ccTLD."
  source: https://moz.com/learn/seo/international-seo

The key point there is are you just providing a translation for users of your base country? Or are you actually selling to different parts of the world and have translated marketing to match.
The second aspect is maintainability I would argue there's not a huge overhead in Magento using TLD vs subfolders but it does make the setup that bit more complex.


text:
Q: Generic parameter for overloaded functions in Scala I'm trying to write a wrapper function that takes either forward or backward because the logic is identical and I want to stick to DRY.
In essence, I want a general function that either uses forward or backward as the function to apply internally. However, forward and backward are both overloaded:
def forward(String, String): String
def forward(Int, String): Int

def backward(String, String): String
def backward(Int, String): Int

Inside my function I want to use something like this:
def move[T](f: (T, String) => T, ...) = ???

Both versions of forward (or backward) are used inside move. Is there a way to pass in forward (or backward) to move while retaining the overloaded capabilities?
Simplified: move returns ( f("text"), f(123) ) and f can be either forward or backward. Is that possible/feasible?
When I try existential types in the parameter type for f the compiler obviously doesn't know what type will be returned, so it picks Any. I'm not too keen on using a Boolean parameter isForward and switch based on that because I still end up copying quite a bit of code.


text:
Q: "A founder of a / the company" What article is correct?

*

*He is a founder of a private company H&M

*He is a founder of the private company H&M?

A: For the first article (a or the founder) 'you would use 'a' if there had been more than one founder, and 'the' if the person was the only founder.
For the second article (a or the private company), you can use either, but you might use 'a' if you think the person hearing or reading has not heard of H&M, or if there are more than one H&M company, and 'the' if you are sure that they have heard of it, and that there is only one.
If you mean the famous clothing company, then it was founded by one person, Erling Persson (he was the founder).


text:
Q: python on windows 10 cannot upgrade modules in virtual environment I has been forced to develop python scripts on Windows 10, which I have never been doing before.
I have installed python 3.9 using windows installer package into C:\Program Files\Python directory.
This directory is write protected against regular user and I don't want to elevate to admin, so when using pip globally  I use --user switch and python installs modules to C:\Users<user>\AppData\Roaming\Python\Python39\site-packages and scripts to C:\Users<user>\AppData\Roaming\Python\Python39\Scripts directory.
I don't know how he sets this weird path, but at least it is working. I have added this path to %Path% variable for my user.
Problems start, when I'm trying to use virtual environment and upgrade pip:

*

*I have created new project on local machine in C:\Users<user>\Projects<project> and entered the path in terminal.

*python -m venv venv

*source venv\Scrips\activate

*pip install --upgrade pip

But then I get error:
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access denied: 'C:\Users\\AppData\Local\Temp\pip-uninstall-7jcd65xy\pip.exe'
Consider using the --user option or check the permissions.
So when I try to use --user flag I get:
ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv.
So my questions are:

*

*why it is not trying to install everything inside virtual enviroment (venv\Scripts\pip.exe)?

*how I get access denied, when this folder suppose to be owned by my user?

When using deprecated easy_install --upgrade pip everything works fine.

A: I recently had the same issue for some other modules. My solution was simply downgrade from python 3.9 to 3.7. Or make an virtual environment for 3.7 and use that and see how it works.


text:
Q: Perl: How to get the list variables that have been used in session file At my workplace we have a webportal that has some core files through which other files are called. So there are some variables for username and project id that everyone uses and are defined in core file. Now I have to avoid using the use strict for using the same variable but i don't want to do it. So how can I get the list of variables that were in the core file? or in basic case how can I get the value in some variable $projectId while using strict.

A: Any variable that is not declared and lexically scoped with my is a package variable. You can refer to a package variable without strict complaining by qualifying the variable name with the package. So if the "core file" defines a variable $projectid in the default main package, you can safely refer to it with
$main::projectid
$::projectid         ($::foo  is the same thing as $main::foo)

or if the "core file" contains a package statement like package ProjectData;, then you would use
$ProjectData::projectid

If the global variable is from the current package (e.g., both the core file and your script are using the default package), then you could also satisfy strict by declaring the variable with the our keyword.
package main;
our $projectid;
# now  $projectid  refers to $main::projectid
...


text:
Q: Adobe Illustrator, Save to Swatches Panel with RGB Hex names instead of RGB 0-255 Values Is there a setting in Adobe Illustrator that would make all saved swatches from the Color Guide save as RGB Hex instead of RGB 0-255 values?
I'm not even sure if this is possible...
It would save a lot of time, allowing me to just double-click the name of each swatch, then copy the hex value, and paste into whatever .css file I'm editing...rather than having to double click the color, click inside the hex box, and copy that way.  For one-off's, thats no big deal, but when dealing with tons of colors, every click adds up time-wise.
Thanks in advance for any suggestions.
Screenshot, showing specifically what I'd like.

A: /*
 Run this script to rename swatch rgb color to  corresponding hex value
 For example, 'R=108 G=125 B=87' will be '#6c7d57'
 Note: script works with RGB color only.
 Befor run script select swatch colors in illustrator's Swathes Panel.
 */

var myDoc = app.activeDocument;
var selSwatches = myDoc.swatches.getSelected();

for (var i=0; i<selSwatches.length; i++)
{
    swcolor = selSwatches[i].color;
    if (swcolor.typename=='RGBColor')
   {
       selSwatches[i].name = rgbToHex(swcolor.red, swcolor.green, swcolor.blue) ;
   }
}

function rgbToHex(r, g, b)
{
        var hex = '#';
        for (var i = 0; i < 3; ++i)
        {
            var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);
            if (isNaN(n) || n < 0 || n > 255)
            {
                return null;
            }
         hex += (n < 16 ? '0' : '') + n.toString(16);
        }
        return hex;
}


text:
Q: Does GAE support Plivo? I've been trying to implement Plivo on my GAE server but I'm getting a 500 error.
I setup Plivo by using Plivo's Github PHP Helper Library. I saved that file as plivo.php on my test server. Then I added plivosend.php with the following code
<?php
if($_POST) {
    require_once 'plivo.php';
    $auth_id = "auth_id";
    $auth_token = "auth_token";

    $p = new RestAPI($auth_id, $auth_token);

    // make sure all 3 params are valid
    if(!empty($_POST['send_to_name']) && !empty($_POST['send_to_number']) && !empty($_POST['sender_name'])) {

        $message = 'this message doesn't matter';
        $plivo_url = 'https://glacial-harbor-8656.herokuapp.com/report';

        // Send message
        $params = array(
                'src' => '15555555555',             // Sender's phone number with country code
                'dst' => $_POST['send_to_number'],    // Receiver's phone number with country code
                'text' => $message,                 // Your SMS text message
                'url' => $plivo_url,                // The URL to which with the status of the message is sent
                'method' => 'POST'                  // The method used to call the url
            );

        // Send message
        $response = $p->send_message($params);

        // Print the response
        $message_uuid = $response['response']['message_uuid'][0];

        if(!empty($message_uuid)) {
            echo '{"success":1,"message_uuid":' . $message_uuid . '"}';
        }
        else {
            // todo log this?
            echo '{"success":0,"error_message":"Message failed to send."}';
        }
    }
    else {
        echo '{"success":0,"error_message":"Message failed to send. Incorrect params."}';
    }
}
?>

On my test server (just my website), this sends without any problems. When I put both plivo.php and plivosend.php on GAE, I get the following 500 error:
207.58.203.50 - - [21/Sep/2015:09:58:00 -0700] "POST /plivosend.php HTTP/1.1" 500 25 - "appname/1.0.2 (iPhone; iOS 9.0; Scale/2.00)" "appname-xxx.appspot.com" ms=4 cpu_ms=3 cpm_usd=0.000003 instance=00c61b117cd04d3645448a84e24daba9991882e1 app_engine_release=1.9.26

I have no idea why... The details are extremely limited.
Does anyone have a clue? Does GAE not support Plivo?

A: Google App Engine restricts many functions (necessary in order to be a massively auto-scaling application platform).  One restriction is outbound HTTP requests (from your PHP code to external).  Read about it here, HTTP Requests and cURL Support for details and options.


text:
Q: Why doesn't Perl threading work when I call readdir beforehand? Whenever I call readdir before I create a thread, I get an error that looks like this:
perl(2820,0x7fff70c33ca0) malloc: *** error for object 0x10082e600: pointer
being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap

What's strange is that it happens when I call readdir before I create a thread (i.e. readdir is not called in any concurrent code). I don't even use the results from readdir, just making the call to it seems to screw things up. When I get rid of it, things seem to work fine. Some example code is below:
opendir(DIR, $someDir);
my @allFiles = readdir(DIR);
close(DIR);

my $thread = threads->create(\&sub1);
$thread->join();

sub sub1 {
print "in thread\n"
}

A: You need to use closedir, not close, to close a directory handle.
Fixing that makes this work correctly, though the symtom I see with close() is a little different:
*** glibc detected *** perl: double free or corruption (!prev): 0x09bc7d28 ***

However, this should still be reported as a bug, since it should be perfectly ok to leave the directory handle to be automatically closed at the end of the program.

A: You will have problems with open dirhandles with all versions of perl up to latest (or two) development version - this problem was fixed recently.
P.S. Use lexical dirhandles.


text:
Q: Is it possible to use the Chrome's devtools when running with Selenium webdriver? I have a Python code that runs a Chrome instance with Selenium web-driver.
In the past, I was able to use the same code and open Chrome's devtools (the inspector, console and the network tabs specifically) while using the webdriver.
I understood that the new chromedriver (I just upgraded it to 2.3.1) is unable to run parallel to the devtools..
I am seeking a way to use the chrome's devtools parallel in order to debug my code. Does someone know a way to do that?
Thanks ahead!

A: As of Chrome 63, this is now possible. See Multi-client remote debugging support.
Go to chrome://version to check what version of Chrome you're on. Chrome updates every 6 weeks, usually. So if you're on Chrome 62, it'll take up to 6 weeks (maximum) to get Chrome 63.

A: Unfortunately, once you start working with the DevTools, ChromeDriver stops working because It has been disconnected.
You can find more information regarding this issue on their official website here.


text:
Q: Ideal equals the whole ring
Show that in the polynomial ring $S=K[x_1, ..., x_n]$, having an ideal $I = (g_1, ..., g_m)$ and ${g_1, ..., g_m}$ a Groebner bases of $I$, then $I = S$ if and only if one of the $g_i$ is a nonzero constant polynomial.

I tried using  using another result: under the same conditions, a polynomial $f \in S$ belongs to $I$ if and only if $f$ reduces to $0$ with respect to ${g_1, ..., g_m}$ but am not 100% sure if everything is correct.
I was also curious if there is another approach.

A: This answer just expands on user26857's excellent hint.
Note that $I=S$ if and only if $1 \in I$.
One direction is trivial. If one of the $g_i$ is a constant, then clearly $I=S$.
Now, if $I=S$, then $1 \in I$. But this implies that $1 \in in(I)=\langle in(g_1),\cdots,in(g_m) \rangle$. All the generators are monomials (i.e. of the form $\vec x^\vec a$ for $\vec a \in \mathbb N_0^n$).

But the only way $1$ can be in an ideal generated by monomials is if $1$ is a scalar multiple of one of the generators. Thus $1 = k \cdot in(g_l)$ for some $l$. Now this implies that $g_l=k$ as well, since $in$ should pick out the highest term.


text:
Q: how to find the path for default pdf reader in ubuntu10.10? i want to give path of document viewer ,which is a default pdf reader with ubunutu10.10 in my java app...
i tried to find the path of app using
$ which documentviewer
on command prompt..but got no result...
Any help is appreciated..

A: Then binary is called evince, as that's the product name. "Document viewer" is just the generic term.

A: It's called evince:
$ which evince
/usr/bin/evince


text:
Q: При подключении к БД пустая строка соединения Пытаюсь загрузить свой небольшой сайтик на хостинг, вроде все нормально, но проблема с подключений к БД. Строка соединения почему-то пустая.
public class ProceduresDB
{
    private string connectionString;
    public ProceduresDB()
    {
        connectionString = WebConfigurationManager.ConnectionStrings["Vocabular"].ConnectionString;
    }
    public void InsertHG(Details dls, string table)
    {
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("Insert" + table, con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@Word", SqlDbType.NChar, int.MaxValue));
        cmd.Parameters["@Word"].Value = dls.Word;
        cmd.Parameters.Add(new SqlParameter("@Value", SqlDbType.NChar, int.MaxValue));
        cmd.Parameters["@Value"].Value = dls.Value;
        cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 1));
        cmd.Parameters["@ID"].Direction = ParameterDirection.Output;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();

        }
        catch (SqlException err)
        {
            throw new ApplicationException(err.Message);
        }
        finally
        {
            con.Close();
        }
    }

Класс с процедурой для работы с базой и файл веб конфиг.
<connectionStrings>
<add name="Vocabular" connectionString="workstation id=Vocabulary.mssql.somee.com;packet size=4096;user id=Air_SQLLogin_1;pwd=**********;data source=Vocabulary.mssql.somee.com;persist security info=False;initial catalog=Vocabulary "
  providerName="System.Data.SqlClient" />
</connectionStrings>


text:
Q: sqlite3 doesnt retain rows after restart im trying to save a row in my settings table, it works all fine and dandy except when i kill the app and then try to get the row back it cant find it
Cursor c = db.query(savedSettings.getTableName(), null, null, null, null, null, null);
    c.moveToLast();
    DatabaseUtils.dumpCursor(c);

    db.setTransactionSuccessful();
    db.endTransaction();

here's how i do my closing:
public void onPause() {
    db.close();
}

public void onDestroy() {
    db.close();
    database.close();
}

public void onStop() {
    db.close();
    database.close();
}

public void onResume() {
    db = database.getWritableDatabase();
}

after i restart the app it loses its contents.
Anyone got any ideas.

A: To preserve data after activity restart.Consider using following code snippet.
@Override
    protected void onSaveInstanceState(Bundle outState)
    {
        Here you will write to things to bundle which you want to preserve
            after activity restart.

        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        Here you will restore the values.
        super.onRestoreInstanceState(savedInstanceState);
    }

Please invest your time in reading
http://developer.android.com/guide/topics/fundamentals/activities.html#SavingActivityState
Hope this help.


text:
Q: Javascript only generates 1 character into field I have a script to generate a 10 character code when a button is clicked. I want to transplant the code into the value field of a input text-box. I believe there is a conflict because the text-box is within a form that has a click(function(event) { attached.
HTML/CSS

<form method="post" action="voucher_add_post.php">

      Voucher value:
      <input type="text" id="value" size="10">

      Code
      <input type="text" id="code" size="20"> <button id="generate">Generate</button>

      How many vouchers?
      <input type="text" id="amount" placeholder="Leave blank for only one voucher" size="40">

    <input type="submit" id="submit" value="Submit" />

</form>

Javascript/JQuery

The problem is it only generates a single character into the value= attribute of the input box with an ID of generate.
If I use the onClick="codeGen()" method of doing it, then it submits the form.

A: I think the issue is in your for loop. You currently have it written as:
for (var i=0; i<length; i++);
code += chars.charAt(Math.floor(Math.random() * chars.length));

But the ; after the for loop declaration terminates the statement. If you rewrite it as:
for (var i = 0; i < length; i++) {
   code += chars.charAt(Math.floor(Math.random() * chars.length));
}

It seems to work.
Fiddle: https://jsfiddle.net/s3ndkpue/

A: The for loop with the semi colon is the issue, however I would also try and simplify the JS + Jquery so it is easier to read as below:
$("#generate").click(function(event) {
  event.preventDefault();

  var code = "";
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i=0; i < 10; i++)
      code += chars.charAt(Math.floor(Math.random() * chars.length));

  $("#code").val(code);
});

Hope that helps :)


text:
Q: Infact of removing, Member from iOS developer program. I developed an iPad Application for one of my client.
It was in-house application. They have Apple Enterprise License. So they invite me as a Admin. So I logged in to their portal and created a distribution certificate and in-house provisioning profile. Using that profile I build the project and created an .IPA file and sent it to the client to distribute among their users.
Now they are planing to delete me from iOS developer program. They are not going to do anything to certificate and provisioning profile I created in their portal. I want to confirm that my app is going to run even after they delete me from their account. I search the web but could not find a trusted source.
Please help.

A: Since I did not get any response I checked it by myself. I created a admin using one of my client's Enterprise account. Then I created a certificate. Then I delete that admin. Then login to the portal using another admin using same machine. I was able to build app using that certificate. So It seems deleting admin account wont effect on the certificate.


text:
Q: 3D array as cv::mat and numpy When I use cv::Mat is it the same as np.array((3,2,3))?
cv::Mat mat_32f_C3(mat.rows, mat.cols, CV_32FC3);
mat_32f_C3.at<cv::Vec3f>(0,0) = cv::Vec3f(1,1,1);
mat_32f_C3.at<cv::Vec3f>(0,1) = cv::Vec3f(2,2,2);
mat_32f_C3.at<cv::Vec3f>(1,0) = cv::Vec3f(3,3,3);
mat_32f_C3.at<cv::Vec3f>(1,1) = cv::Vec3f(4,4,4);
mat_32f_C3.at<cv::Vec3f>(2,0) = cv::Vec3f(5,5,5);
mat_32f_C3.at<cv::Vec3f>(2,1) = cv::Vec3f(6,6,6);

I am not sure if the cv::Vec3f represents RGB in a color image.
In python I would write
broadcast = np.zeros((3,2,3))
i1 = np.arange(1, 7, 1).reshape((3,2))
result = i1 + broadcast

output array([[[[1., 2.],
         [3., 4.],
         [5., 6.]],
        [[1., 2.],
         [3., 4.],
         [5., 6.]],
        [[1., 2.],
         [3., 4.],
         [5., 6.]]]])

Are these examples the same?


text:
Q: Narrow down allowed types in templated using type alias with static_assert While still learning template based meta programming, I've come to the following problem:
I've got a templated using type alias, and I want to narrow down the allowed types with static_assert but I'm not sure how to write it:
using service_func_plain_loop_t = std::function<void(void)>;
using service_func_with_arg_loop_t = std::function<void(std::string)>;
using service_callbacks_t = std::map<event, std::function<bool(void) >>;

template<typename service_loop> using service_functionality_t =
std::pair<service_loop, service_callbacks_t>;
static_assert(
        std::is_convertible<service_loop,service_func_plain_loop_t>.value ||
        std::is_convertible<service_loop,service_func_with_arg_loop_t>.value,
        "service_loop has to be either service_func_plain_loop_t or "
        "service_func_with_arg_loop_t");

This approach fails because of service_loop is not declared in the scope of static_assert. When checking classes I can just move the assert into the class scope, but what's the syntax here?

A: You could write a helper class to do the static_assert:
template <typename service_loop>
struct service_functionality {
    static_assert(
        std::is_convertible<service_loop,service_func_plain_loop_t>::value ||
        std::is_convertible<service_loop,service_func_with_arg_loop_t>::value,
        "service_loop has to be either service_func_plain_loop_t or "
        "service_func_with_arg_loop_t");

    using type = std::pair<service_loop, service_callbacks_t>;
};

template<typename service_loop> using service_functionality_t =
typename service_functionality<service_loop>::type;

Note also that it should be std::is_convertible<T,U>::value or std::is_convertible<T,U>{} rather than std::is_convertible<T,U>.value. Although we'll likely get std::is_convertible_v<T,U> helper variable templates in C++17.
Live Demo


text:
Q: Why move_uploaded_file method does not work in WordPress? I created a metabox in wordpress for uploading photo to my plugin custom directory. I used the following code
<form  method="post" enctype="multipart/form-data">
<input type="file" name="taggr_upload">
</form>

This is the form I created in side the add_meta_box() method
Then I add this save_post action hook
add_action( 'save_post', 'boj_mbe_save_meta' );

function boj_mbe_save_meta( $post_id ) {
        move_uploaded_file($_FILES['taggr_upload']['tmp_name'], 'photo/'. basename( $_FILES['taggr_upload']['name'] ));
}

Why it doesn't save into my photo folder when I open my folder?
This is the full code:
<?php
/*
Plugin Name: random plug
Plugin URI: http://example.com/wordpress-plugins/my-plugin
Description: A plugin demonstrating Cron in WordPress
Version: 1.0
Author: Brad Williams
Author URI: http://wrox.com
License: GPLv2
*/

add_action('init', 'register_tagging_post');

 function register_tagging_post(){
       $tagging_args = array(
           'public' => true,
           'supports' => array(
               'title',
               'thumbnail'

           ),
           'query_var' => 'tagging',
           'rewrite' => array(
              'slug' => 'tagging',
              'with_front' => false
           ),
            'labels' => array(
            'name' => 'Albums',
            'singular_name' => 'Album',
            'add_new' => 'Add New Album',
            'add_new_item' => 'Add New Album',
            'edit_item' => 'Edit Album',
            'new_item' => 'New Album',
            'view_item' => 'View Album',
            'search_items' => 'Search Albums',
            'not_found' => 'No Albums Found',
            'not_found_in_trash' => 'No Albums Found In Trash'
        ),
       );

       register_post_type('tagging', $tagging_args);
 }

 //add metabox
 add_action( 'add_meta_boxes', 'boj_mbe_create' );

function boj_mbe_create() {
    //create a custom meta box
    add_meta_box( 'boj-meta', 'My Custom Meta Box', 'boj_mbe_function', 'tagging', 'normal', 'high' );
}

function boj_mbe_function( $post ) {
    //retrieve the meta data values if they exist
    ?>
    <form  method="post" enctype="multipart/form-data">

     <input type="file" name="taggr_upload">
    </form>

    <?php
         echo WP_PLUGIN_DIR;

//hook to save the meta box data
add_action( 'save_post', 'boj_mbe_save_meta' );

function boj_mbe_save_meta( $post_id ) {
    //verify the meta data is set
    if ( isset( $_POST['taggr_upload'] ) ) {
        //save the meta data

       $path_to_plugin = WP_PLUGIN_DIR . '/yeah';
     move_uploaded_file($_FILES['taggr_upload']['tmp_name'], $path_to_plugin . '/photo/'. basename( $_FILES['taggr_upload']['name'] ));
    }
}

//create custom post column
}
?>

Why it doesn't work?

A: EDIT
Okay first of all, you can not upload a file from any of the metaboxes. Reason? Well, because WordPress wraps all of the post stuff inside a <form> which does not have the necessary attributes to upload files.
So the solution is to provide an option to upload using WordPress default media uploader and save the URL instead.
Here is a working example. Please use this as a guide, not as your production code. In reality you'd like to fine tune the media uploader button so that multiple button can add multiple urls to multiple inputs.
http://example.com/wordpress-plugins/my-plugin
    Description: A plugin demonstrating Cron in WordPress
    Version: 1.0
    Author: Brad Williams
    Author URI: http://wrox.com
    License: GPLv2
    */
add_action( 'init', 'register_tagging_post' );

function register_tagging_post() {
    $tagging_args = array(
        'public' => true,
        'supports' => array(
            'title',
            'thumbnail'
        ),
        'query_var' => 'tagging',
        'rewrite' => array(
            'slug' => 'tagging',
            'with_front' => false
        ),
        'labels' => array(
            'name' => 'Albums',
            'singular_name' => 'Album',
            'add_new' => 'Add New Album',
            'add_new_item' => 'Add New Album',
            'edit_item' => 'Edit Album',
            'new_item' => 'New Album',
            'view_item' => 'View Album',
            'search_items' => 'Search Albums',
            'not_found' => 'No Albums Found',
            'not_found_in_trash' => 'No Albums Found In Trash'
        ),
    );
    register_post_type( 'tagging', $tagging_args );
}

//add metabox
add_action( 'add_meta_boxes', 'boj_mbe_create' );

function boj_mbe_create() {
    //create a custom meta box
    add_meta_box( 'boj-meta', 'My Custom Meta Box', 'boj_mbe_function', 'tagging', 'normal', 'high' );
}

function boj_mbe_function( $post ) {
    $file_meta_data = get_post_meta( $post->ID, 'taggr_file', true );
?>
<input type="text" class="regular-text" name="taggr_file" id="taggr_file" value="<?php echo $file_meta_data; ?>" />
<button id="taggr_upload" class="button-primary">Upload</button>
<script type="text/javascript">
    jQuery(document).ready(function($) {
        // Uploading files
        var file_frame;
        jQuery('#taggr_upload').on('click', function( event ) {

            event.preventDefault();

            // If the media frame already exists, reopen it.
            if ( file_frame ) {
                file_frame.open();
                return;
            }

            // Create the media frame.
            file_frame = wp.media.frames.file_frame = wp.media({
                title: jQuery( this ).data( 'uploader_title' ),
                button: {
                    text: jQuery( this ).data( 'uploader_button_text' ),
                },
                multiple: false  // Set to true to allow multiple files to be selected
            });

            // When an image is selected, run a callback.
            file_frame.on( 'select', function() {
                // We set multiple to false so only get one image from the uploader
                var attachment = file_frame.state().get('selection').first().toJSON();
                // Do something with attachment.id and/or attachment.url here
                $('#taggr_file').val(attachment.url);
            });

            // Finally, open the modal
            file_frame.open();
        });
    });
</script>
    <?php
}

//hook to save the meta box data
add_action( 'save_post', 'boj_mbe_save_meta' );

function boj_mbe_save_meta( $post_id ) {
    //verify the meta data is set
    if ( isset( $_POST['taggr_file'] ) ) {
        update_post_meta( $post_id, 'taggr_file', stripslashes( $_POST['taggr_file'] ) );
    }
}

If you're still facing any problem, then feel free to reply :)


text:
Q: SSL encrypted Websockets in Java Using Java WebSockets API So, I have been using the Java Websockets API to create a WebSocket server in Java, which worked just fine, until I realized I should be using an SSL encrypted connection using "wss:myurl.tld". Basically, the API wants an SSLContext object to work with SSL, but I can't for the life of me figure out how to make one of those.
I looked at some examples and found out that if I could make a Java KeyStore file with a certificate I could make it work, so I tried to do that.
I started fiddling around with trying to get a "Let's Encrypt" certificate following these instructions but I ran into to some problems.

*

*I run windows and I could find no software using the Let's Encrypt system that worked the same as in the instructions, and homebrew on my mac machine is broken, and it's running a too old OS to update.

*Being rather inexperienced with SSL I had no real idea what to put in as parameters.

So, in short, how do I make my Java Websocket server use a secure SSL connection?
Oh, and pardon my messy English and lack of question-writing skills, I'm a bit new to these sorts of things.


text:
Q: count occurrences in a NSArray this is a part of my code from a NSArray:
2012-06-03 16:03:45.140 test[4178:f803] data (
        {
        receiver = david;
        sender = james;
        idMessage = 248;

    },
        {
        receiver = david;
        sender = james;
        idMessage = 247;

    },
        {
        receiver = david;
        sender = Marc;
        idMessage = 246;

    }

)

I want the number of messages sent by sender to receiver or something like that
james = 2;
marc = 1;

A: "data" is the NSArray, which appears to contain NSDictionary objects.
So you'd want to loop through the array this way:
NSNumber * countOfSender;
NSString * nameOfSender;
NSMutableDictionary * countDictionary = [[NSMutableDictionary alloc] initWithCapacity: 1];

// go through the original array to examine each sender
for(NSDictionary *anEntry in data)
{
    nameOfSender = [anEntry objectForKey: @"sender"];
    if(sender)
    {
       countOfSender = [countDictionary objectForKey: nameOfSender];
        if(countOfSender == NULL)
        {
            // create a new count entry for this particular sender
            countOfSender = [NSNumber numberWithInt: 1];
        } else {
            // increment the previous count
            countOfSender = [NSNumber numberWithInt: [countOfSender intValue] + 1];
        }
        [countDictionary setObject: countOfSender forKey: nameOfSender];
    }
}

// now print out the outputs
for(nameOfSender in [countDictionary allKeys])
{
    countOfSender = [countDictionary objectForKey: nameOfSender];
    NSLog( @"%@ : %d" nameOfSender, [countOfSender intValue] );
}

A: You would do something like..
NSMutableArray *array = [NSMutableArray array];
for(id object in yourArray) {

    NSLog("sender:%@ id:%i",[object valueForKey:@"sender"],[[object valueForKey:@"idMessage"] intValue]);

   NSMutableDictionary *dict = [
   NSMutableDictionary dictionary];
   [dict setValue:[object valueForKey:@"sender"] forKey:@"sender"];
   [dict setValue:[NSNumber numberWithInt:[[object valueForKey:@"idMessage"] intValue]] forKey:@"idMessage"];

   [array addObject:dict];
}

NSLog(@"%@",array);


text:
Q: MySqlQuery taking too long time to execute I have Four Schema in MySQL. Each Schema contains multiple tables. I have around 50000 records in all Schema. When I execute insert or update query it's taking me around 2 minutes 30 seconds to execute.
I tried the following ways

*

*query cache disabled

*Increased buffer size approximate 5 GB

*default lock timeout

My server RAM is 8 GB
Any help will be appreciated. Thanks


text:
Q: Why it caused SIGSEGV (signal 11) (core dumped)? Here I have function which gets a string array from struct and returns struct integer_array.
#include "string.h"
#include "stdlib.h"
integer_array* my_count_on_it(string_array *p1)
{
    integer_array *pusher;
    int size = p1->size;
    char** str = p1->array;
    pusher = (integer_array*) malloc(size*sizeof(integer_array));

    for (int i = 0;i<size;i++)
    {
        pusher->array[i] = strlen(str[i]);
    }
    return pusher;
}

Function prototype(c):
  typedef struct s_string_array {
    int size;
    char** array;
  } string_array;

 typedef struct s_integer_array {
   int size;
   int* array;
 } integer_array;

@param {string_array*} param_1
@return {integer_array*}

integer_array* my_count_on_it(string_array* param_1) {

}

This is how should it work

Input/Return Examples:
Input: ["This", "is", "the", "way"]
Return Value: [4, 2, 3, 3]
Input: ["aBc"]
Return Value: [3]

A: integer_array *pusher is initialized well. But the individual pointers in it should also be initialized. You may probably want to do this pusher->array = (int*) malloc(sizeof(int) *size) . But honestly speaking, I did not get a grasp on what you wanted to achieve with that function call. You declared an array of integer_array but you seem to use only the  first element, I suspect their is a potential logic error in your code.
Edit: As @David C. Rankin mentioned, it may also be that you did not assigned a valid value for p1->array
You may want to have your functions like this.
#include "string.h"
#include "stdlib.h"
#include "stdio.h"

typedef struct s_string_array {
    int size;
    char** array;
} string_array;

typedef struct s_integer_array {
    int size;
    int* array;
} integer_array;

integer_array* my_count_on_it(string_array *p1)
{

    integer_array* pusher = (integer_array*) malloc(sizeof(integer_array));

    pusher->size = p1->size;
    pusher->array = (int*) malloc(sizeof(int) * p1->size);

    for (int i = 0; i < p1->size; i++)
    {
        pusher->array[i] = strlen(p1->array[i]);
    }
    return pusher;
}

int main()
{
    string_array *p1 = NULL;

    /* collect data from user */

        // Setup p1{} struct

    integer_array* pusher = my_count_on_it(p1);

    for (int i = 0; i < pusher->size ; i++)
        printf(" %d ", pusher->array[i]);

    return 0;
}


text:
Q: Mapping integer to alphabet and print all combination base on a 3 digit input I was given this question by a co-worker:
Given that: '1' match to 'a', '2' to 'b' , '3' to 'c'...like wise... '26' to 'z'.
How can I get an output that follow this pattern :
if I get an input d="111", the output should be: aaa, ak, ka
/ (111)->aaa, (1, 11)->ak, (11,1)->ka
I create the following script, but I know that it is too long.
str1 = ""
str2=""
str3=""
d = "101"

for i in d:
    if "0" in i:
        pass
    else:
        str1 += chr(int(i)+96)

if int(d[0]) == 1:
    str2 += chr(int(d[0]+d[1])+96)
    str2 += chr(int(d[2])+ 96)
elif int(d[0]) == 2 and int(d[1]) < 7 :
    str2 += chr(int(d[0] + d[1]) + 96)
    str2 += chr(int(d[2]) + 96)
if int(d[1]) == 1:
    str3 += chr(int(d[0])+ 96)
    str3 += chr(int(d[1]+d[2])+96)
elif int(d[0]) == 2 and int(d[1]) < 7 :
    str3 += chr(int(d[1] + d[2]) + 96)
    str3 += chr(int(d[0]) + 96)

print str1
print str2
print str3

I would like to know a better way to tackle this.

A: Building on both K. Weston's and bigballer's answer, here is what I would do.

*

*create a dict to map numbers to letters

*recurse over the permutations of the input to get possible outputs
letters = 'abcdefghijklmnopqrstuvwxyz'
values = {
    i + 1: x for i, x in enumerate(letters)
}

def permutations(st):
    # we only need 1, 2 here because letter values are always less than one digit
    # don't worry about the '01' corner case since it wasn't defined in the problem, but easy to avoid with an extra if
    for x in range(1, 3):
        value = st[:x]
        # avoid yielding the same substring twice for 1-character st
        if len(val) < x: continue
        next_ = st[x:]
        value = int(value)
        # make sure our value maps to a letter
        # in 'a'..'z'
        value = values.get(value)
        if value is not None:
            if next_:
                for y in permutations(next_):
                    yield value + y
            else:
                yield value

And since this is a generator function, you can use it like this:
for x in permutations('111'):
    print x

A: You could use a dictionary:
A dictionary is just like an array, but it has key-value pairs.
For example:
alphabet = {1 : 'a', 2: 'b', 3: 'c'}
print alphabet[1]
>a

In your case:
print alphabet[int(i)]

if i were 3 it would print 'c'.
Hope that helps

A: edit, i completed to code for you, the trick is that since the alphabet is small, we can brute force generate every combination of letters and store them in a lookup table:
from itertools import product
from string import lowercase
from collections import defaultdict
d = defaultdict(list)
for r in (2, 3):
    for p in product(lowercase,repeat=r):
         p = list(p)
         d[''.join(map(str,(ord(i) - ord('a') + 1 for i in p)))].append(p)

print d['111']
#[['a', 'k'], ['k', 'a'], ['a', 'a', 'a']]

print d['126']
#[['a', 'z'], ['l', 'f'], ['a', 'b', 'f']]


text:
Q: How to make bootstrap columns scrollable? I want to make this card x-scrollable. But after three blocks, the fourth block is rendering in the new line.
I want to scroll horizontally. I tried everything from past 5 days.
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="ie=edge" http-equiv="x-ua-compatible">
    <title></title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

Please make this scrollable horizonally

                            Heading

                            <form method="post">

                            </form>

css:
.customClass {
  overflow-x: auto;
  white-space: nowrap;
}
.customClass .col-md-4 {
  display: inline-block;
    float: none;
}

Codepen link: https://codepen.io/maharshi9999/pen/qBddebG

A: just remove the row class. Use what you have just remove that class as boom done!

if want something different to your approach, let me know.
Good luck!

A: Bootstrap 4 uses flex. In case if you want override the wrapping sytle of Bootstrap row you have to use flex-wrap:nowrap; for row.
https://codepen.io/rohinikumar4073/pen/Exjjqzx

.row.customClass {
  overflow-x: auto;
  flex-wrap: nowrap;
}
<!DOCTYPE html>

 <meta charset="utf-8">
 <meta content="ie=edge" http-equiv="x-ua-compatible">
 <title></title>
 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

Please make this scrollable horizonally

       Heading

       <form method="post">

       </form>

A: I removed col-md-4 classes as well as set the width to customClass.

.card-body {
  overflow-x: scroll;
}
.customClass {
  width: 1500px;
}

<!DOCTYPE html>

 <meta charset="utf-8">
 <meta content="ie=edge" http-equiv="x-ua-compatible">
 <title></title>
 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

Please make this scrollable horizonally

       Heading

       <form method="post">

          <di class='col'>

          </di>

       </form>


text:
Q: (Why) does jQuery make my slider look fat? I'm teaching myself jQuery and starting on jquery-ui using a slider control.  I have it hooked up and functionally it works well, setting some global page variables when I slide the handle.  It does not, however, look like the slider on the jquery-ui demo page.
It's a horizontal slider and I can control the length of the bar by setting the CSS width property of the  that jquery-ui converts to the slider.  But the bar is about two or three times "thicker" than the one on the demo page, and the slider handle is proportionately larger.  It looks ok, but not as good as the one on the demo page.
Taking the width setting as a hint, I tried setting the CSS height property of the underlying .  That changed the height of the bar part, but not the handle which now looked outsize.
Here is the header:

    <title>The Memory Game</title>
    <link href="css/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />
    <link href="css/memoryGame.css" rel="stylesheet" type="text/css" />

Here is the HTML markup:

Here is my CSS for control-panel:
div#control-panel {
padding:    10px;
float:      right;
}

And here is the jQuery in which I apply the slider:
$('#slider').slider({
    max: 10000,
    value: waitTime,
    change: function(event, ui) {
        waitTime = ui.value;
        fadeTime = waitTime / 3;
    }
});

Can anyone suggest how I can scale the thickness of my slider or at least get the same thickness shown on the jquery-ui demo page?

A: The slider size is controlled by the 'font-size' css property. You want to decrease the font-size of the parent element.

A: All jQuery UI widgets have theming instructions associated with them. The instructions for the slider widget mention certain CSS classes that are assigned to the slider handle.
Looking at the jquery-ui.css (or ui.slider.css if you are using the development package) you can see that the default CSS is something like:
.ui-slider .ui-slider-handle {
  width: 1.2em;
  height: 1.2em;
}
.ui-slider-horizontal .ui-slider-handle {
  top: -0.3em;
  margin-left: -0.6em;
}

You can override these CSS rules to create a handle of any size.
Edit
I've produced basic slider functionality here: http://jsbin.com/otika3 (Editable via http://jsbin.com/otika3). Please try and reproduce your problem on http://jsbin.com and share the public link with us.
Full source:
<!doctype html>

  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css" type="text/css" />

  <title>http://stackoverflow.com/questions/1616675</title>


text:
Q: Array issue in Data Fusion I'm currently in the process of integrating MongoDB database into BigQuery through Data Fusion and I'm facing an issue with array objects. It seems like Data Fusion doesn't understand or support such data types. However it seems to be a feature that I could use and here's where I get confused. Let me give you an example based on one row of data.
Order_number, items
43324         [{"name":"x","price":"10"},{"name":"y","price":"20"}]

From what I've been testing, the only thing that I can do (that works) is to flatten items, then parse it as json and achieve such result:
Order_number, items_name, items_price
43324              x           10
43324              y           20

However, I'm trying to avoid duplicating the order number and I want to leave items as array to have this kind of result in one row:
Order_number,       items_name,      items_price
43324                 x                   10
                      y                   20

Here's my workflow in Data Fusion

And here's my output schema generated in wrangler (I've added only name for testing purposes):

I propagated this schema into BigQuery and here's an error that I'm getting:
Spark program 'phase-1' failed with error: null.

So clearly, there's an option to work with arrays in Data Fusion but something seems to be off and I don't know what. I've tested every single possiblity or combination and I wasn't able to achieve any positive result.
The alternative approach that gave any reasonable error was this:

And this returns the following error:
Spark program 'phase-1' failed with error: Unable to decode array 'items'

Maybe I need to add some directives or another plugin in Data Fusion but honestly I'm running out of ideas. I'd aprreciate any suggestions on the matter.

A: The wrangler has a problem processing nested arrays/records, couldn't manage to make it work. My recommendation, use a JS transform to process the data and generate the right json structure to be loaded on bigquery.
Send all data from gcs in one line to the js transform and split/parse the json, generate an object as you want to send to the BQ sink. I haven't processed data on it, but I imagine it will be a workaround due to the wrangler limitation.


text:
Q: How do I make an If event in batch when a ping fails? I know this has been asked many times before but it's a bit different in my situation.
"If errorlevel 1" does not work in my case
When I ping something like my router when my ethernet is unpluged than it won't return a "timeout" it will return a "general failure" the statement "if errorlevel 1" won't detect it so I'm getting a response saying that it's reachable when it's not and it won't detect the "general failure" as an error.
I was thinking maybe it's possible to make a line checking the response (in ascii) to check if it's "General Failure" but I wouldn't know how to do that either.
Is there a way to get past this problem or is this the limit of batch?

A: Try like this :
ping "www.whatever.com" && echo OK || echo Connection Problem

for more explaination :
http://www.robvanderwoude.com/condexec.php


text:
Q: How can I reference a dynamically created control in VBA? I've been finding the answers I need here on StackOverflow for months (thank you all!) but so far my search terms aren't finding the result I need this time... hence, my first post here...
I have an Excel file that includes two UserForms:

*

*The first is used to input certain invoice data and then export that data in a format that can be uploaded into our proprietary accounting system.

*The second is later used to post payment data against those invoices and then, similarly, export that data in a format that can be uploaded into our accounting system.

The second form has to be created dynamically in Userform_Initialize, because the number of payments required (and, thus, the number of TextBox and Label controls created) varies depending on the size of the invoices.  I've finished the code to create this second form and it works well, but I'd like to add some functionality that is triggered when some of these dynamically created controls are changed by the user.
I've done this in other forms using a given control's _Change() procedure (for example, when I want to move to the next box after entering a dollar amount, I use _Change() to SetFocus elsewhere as soon as the value has two digits after the decimal).  So my question is: how can I establish _Change()-style procedures for controls that don't yet exist before the form is initialized?  Is there a way to set a "global" _Change() procedure that I can use to loop through text boxes and use if/then/else statements based on their dynamic names?
Any tips would be greatly appreciated!

A: When I am using dynamic forms, I like to create object arrays to store the relevant information so that I can quickly and easily reference the objects by "name".


text:
Q: How do I escape string literals using regex for my lexer? Right now, I'm writing a lexer, and I want to be able to match a string token while taking into account escape characters.
So, I wish to be able to parse things like this:

*

*'Hello World' as [', Hello World, '],

*'There\'s an apostrophe in here' as [', There's an apostrophe in here, ']

*'This is a backslash: \\' as [', This is a backslash: \, '].

Currently, I have the following regex rule for matching strings: /^\s*(')(.*?)(')/s. ^\s* accounts for leading whitespace, while (')(.*?)(') matches the string 3 times: an opening token, the string itself, and finally a closing token. Once I've recognised a token, I push the matched tokens into an array, and delete the full match from the beginning of the data I'm working with.
I've tried to modify my rule to account for escaped characters, but I haven't been able to make it work, and to be frank, I don't really know where to go from here. I'm at a loss for what to even try. If I check for a backslash, it won't work for two. If I check for two, it won't work for three, etc.
Could someone put me on the right track for how to implement this? This aside, my lexer is already finished and does what it have to do. This is the only thing that remains.

A: You may use
/^\s*(')([^'\\]*(?:\\.[^'\\]*)*)(')/s

See the regex demo.
Details

*

*^ - start of string

*\s* - 0+ whitespace chars

*(') - Capturing group #1: a ' char

*([^'\\]*(?:\\.[^'\\]*)*) - Capturing group #2:

*

*[^'\\]* - 0+ chars other than '  and \

*(?:\\.[^'\\]*)* - 0 or more repetitions of:

*

*\\. - a \ followed with any char

*[^'\\]* - 0+ chars other than '  and \

*(') - Capturing group #3: a '.


text:
Q: searching strings from a file into another file in c I have a text file(names.txt) with single names like:
mary
john
kj
mark

Am trying to match them with other data in another text file(records.txt),it looks like this:
mary jon mik 200 west 90
fgg gh 400 east 700
james ggg 890 south 800
john nike 556 4666

Am reading names.txt and running the names against records.txt , if a name matches the entire line in records.txt is printed. When i feed the names one by one from CL,it is ok.But when i adapt the code to do as above from a text file , its not working.Can someone please point me to the right direction.Here is my code:
/*program to search for a given string from a file*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int usage(char*argv[]);

 int main (int argc,char*argv[])
 {
  int flag=0,i=0;
  FILE*fp,*lp;
  char line[50];
  char word[10];

  lp=fopen(argv[1],"r");
  fp=fopen(argv[2],"r");

  if (argc!=3) {
     usage(argv[0]);
 exit(0);
  }

  if (lp==NULL || fp==NULL) {
 perror("can't open file");
  exit(1);
   }

  //getting words to search

  while (fgets(word,10,lp)!=NULL) {

     for(i=0;i<=strlen(word);i++){
        if(word[i]=='\n'){
          word[i]='\0';
          break;
         }
      }
    printf("searching for %s in %s ",word,argv[2]);
     //searching in file
    i=0;
    while (fgets(line,50,fp)!=NULL) {
     i++;
     if(strstr(line,word)!=NULL){
       printf("%s found in line %d\n%s.\n",word,i,line);
       flag=1;
 }
  }
  if(flag==0)
    puts("no match found");
  flag=0;
 }
 putchar('\n');
 exit(0);

}
int usage(char*argv[])
{
  printf("usage:\n<argv> <source file> < search file>\n");
  return 0;
 }

Running the above code this is what am getting:
  searching for mary
  in records.txt
  jon mik mary 56 567

  mary found in line 1
  jon mik mary 56 56

  searching for john
  in records.txt
  no match found
  searching for kj
  in records.txt
  no match found
  searching for mark in records.txt
  no match found

A: The first issue is that you are not stripping the white space from the end of word and then you are also appending a space and I am not sure why. With minimal changes if you iterate over word each time you read a new line and replace the first \n with \0 that will fix that.
The second issue is that you are only iterating over the contents of the second file once and so you are only comparing the words in names.txt against the first line in records.txt.
You also need to reset flag back to 0.


text:
Q: CSS Attribute Selectors role*=user Can anyone explain to me, please, what the following CSS selector will target?
[role*=user] > article a:not([href^=stage]) {
    /* some rules here */
}

A: The selector is targetting any anchor tag [a] which its href attribute doesn't start with stage [:not([href^=stage])]; that, is inside the an article, which is a direct child > of an element on which its role attribute contains user.
In the example bellow I styled the targets with a pinky color so that it can give an idea of what elements are selected by that:

[role*=user] > article a:not([href^=stage]) {
    color: fuchsia;
}

    loren ipsum dolor sit amet


text:
Q: .startsWith throws error while using typescript Whenever I use .startsWith(), it gives me this error:
Property 'startsWith' does not exist on type 'string'.

It works if I try .startsWith() on index.js, but not index.ts.
Here is what I have:
client.on("message", function (msg) {
    if (msg.author.bot) {
        return;
    }
    if (!msg.content.startsWith(ConfigFile.config.prefix)) {
        return;
    }
    msg.channel.send(msg.author.username + " this better work.");
});


text:
Q: ImageMagick complains when image is missing while stitching together tiles of an image I have to stitch together pictures (first vertically, then horizontally) with a varying amount of tiles via the command line on macOS 10.14.5. I usually use this command:
convert -append 0_0.jpeg 0_1.jpeg 0_2.jpeg 0_3.jpeg 0_4.jpeg 0_5.jpeg 0a.jpg &&
convert -append 1_0.jpeg 1_1.jpeg 1_2.jpeg 1_3.jpeg 1_4.jpeg 1_5.jpeg 1a.jpg &&
convert -append 2_0.jpeg 2_1.jpeg 2_2.jpeg 2_3.jpeg 2_4.jpeg 2_5.jpeg 2a.jpg &&
convert -append 3_0.jpeg 3_1.jpeg 3_2.jpeg 3_3.jpeg 3_4.jpeg 3_5.jpeg 3a.jpg &&
convert -append 4_0.jpeg 4_1.jpeg 4_2.jpeg 4_3.jpeg 4_4.jpeg 4_5.jpeg 4a.jpg &&
convert -append 5_0.jpeg 5_1.jpeg 5_2.jpeg 5_3.jpeg 5_4.jpeg 5_5.jpeg 5a.jpg &&
convert -append 6_0.jpeg 6_1.jpeg 6_2.jpeg 6_3.jpeg 6_4.jpeg 6_5.jpeg 6a.jpg &&
convert +append 0a.jpg 1a.jpg 2a.jpg 3a.jpg 4a.jpg 5a.jpg 6a.jpg 0_final.jpg

where I first add all corresponding tiles vertically (here 6 tiles) and then add all columns (here 7) horizontally to the final picture.
The issue is that sometimes, I have less pictures in a column (0 to 4 instead of 0 to 5 as given here) or more columns (0 to 10 instead of 0 to 6 as shown here).
Is it possible to adjust the above command so that imagemagick does not complain that, for example, picture 0_5.jpg or 7_0.jpg does not exist? Currently imagemagick complains and stops the process of stitching together the existing tiles.

A: You should be able to do this with wildcards. The shell will expand to existing files:
convert -append 0_*jpeg 0a.jpg &&
convert -append 1_*jpeg 1a.jpg &&
convert -append 2_*jpeg 2a.jpg &&
convert -append 3_*jpeg 3a.jpg &&
convert -append 4_*jpeg 4a.jpg &&
convert -append 5_*jpeg 5a.jpg &&
convert -append 6_*jpeg 6a.jpg &&
convert +append *a.jpg 0_final.jpg


text:
Q: Yii-2 how to sum up the values of an object returned from json? I have a json response. In the response, I have an object named xhqd. Now, I want to add all these values. Below is my json
{
"details": [
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T16:39:46",
        "xhqd": "15",
        "i": 0
    },
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T16:41:48",
        "xhqd": "18",
        "i": 1
    },
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T16:43:50",
        "xhqd": "18",
        "i": 2
    },
    .
    .
    .
    .
    .
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T17:06:07",
        "xhqd": "19",
        "i": 13
    }
  ]
}

How can I do 15+18+18+....+19 in Yii2?
Any help would be highly appreciated

A: Yii has a helper class Json it contains a method Json::decode use it to decode the json string.
Dont forget to add namespace use yii\helpers\Json;
$jsonData = '{
"details": [
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T16:39:46",
        "xhqd": "15",
        "i": 0
    },
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T16:41:48",
        "xhqd": "18",
        "i": 1
    },
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T16:43:50",
        "xhqd": "18",
        "i": 2
    },
    .
    .
    .
    .
    .
    {
        "zdjh": "002999001180",
        "sjsj": "2018-07-03T17:06:07",
        "xhqd": "19",
        "i": 13
    }
  ]
}';

$json_decode =  Json::decode($jsonData);
$total = 0;
foreach($json_decode as $key => $value){
    foreach($value as $valuesKey => $valdata){
         $total += $valdata->xhqd;
    }
}

echo $total;


text:
Q: Visual Studio Unexpectedly Adding Feature on Load I have a SharePoint 2010 solution in Visual Studio 2013. Every time I close and reopen Visual Studio, a new feature is added to the solution with one list inside it. The list was removed from another feature that it should be in. It is always the same list. As soon as I open the solution this pops up in the Output window before I do anything...

A new feature Feature2 has been added to the project Solution
C:\Code\Solution\Package\Package.package (0,0): Added Feature2 to Package

What is causing this?
I have tried the following:

*

*Recreated the solution and copied all files over - No change

*Checked the package and project manifest. - Everything looks okay.

*Loaded the project every different way, including unload and reload command. - No change

*Recreated the list it likes to isolate into its own feature - No change

*Recreated the feature the list should be in but it keeps moving to this new feature - No change

*Added a new list and put it after the problem list in the feature - VS then created 3 new features! It took 3 lists out of my feature and put one in each of its own features. I guess I made it angry.

A: If the lists in the same feature have the same Type ID, the tooling will move the lists into a newly created feature, because the Type must be unique within a feature. You can check the documentation on the ListTemplate element for more information.

A: It is because features cannot contain list templates that have identical values for Type. This is explained here: https://msdn.microsoft.com/en-us/library/office/ms462947.aspx

Type
Optional Integer.
Provides a unique identifier for the template. This identifier must be unique within the feature, but need not be unique across all feature definitions or site definitions. For a list of the default list template types, see SPListTemplateType.

You will probably find that your Elements.xml file for your list templates contains the same value for Type.
To fix this, you will need to edit the Elements.xml files of the list template and the list instance.

*

*Change the Type of the ListTemplate xml element to a unique integer.

*Change the TemplateType of the ListInstance xml element to the same integer

I have started to choose numbers over 1000 to avoid conflicts (Although 1100, 1200, 1220 and 1221 are system types)


text:
Q: oauth 1.0a api, use without logging in I want to use Tumblr's api to pull down some images from blogs.
I was looking through their api and it is oauth 1.0a  , I don't want my user to have to log in, nor do I expected them to have a tumblr account, I just want to dynamically display content from a blog
is this possible with oauth? I'm not sure I have a complete fundamental understanding of that protocol to answer this question mentally

A: Supporting Oauth does not necessarily mean the end user has to provide credentials.  In fact, while Tumblr does use OAuth, they don't actually require it for their api calls that just pull published data, including the one I believe you are interested in.  You will need to register your application here: http://www.tumblr.com/oauth/apps to get an api key, but then you should be able to access the blog information you are looking for.  I put together a sample scenario on theRightAPI here:  http://therightapi.com/tDWRFGE that shows how this API can be called with the appropriate data.  You can specify a different blog name with a tag of your liking and your api key (I inserted one from their samples) and you can verify whether you get back the result you are expecting.
Hope this helps!


text:
Q: converting jpg to .mp4 by ffmpeg I have 320 jpg (320x574) images which I recorded with 2000 fps. I want to make a .mp4 video of them. I have run below codes in cmd (win7) and when I run the code it is working and gives me the MP4 file and I can see the video, but this attention note pops up in the cmd:

Frame rate very high for a muxer not efficiently supporting it

and asked me to use other muxer or -vsync 2.
ffmpeg -f image2 -i Path/To/File/filename%d.jpg -r 2000 -pix_fmt yuv420p    path\to\result\test.mp4

I also tried this code with -vsync 2
 ffmpeg -f image2 -i Path/To/File/filename%d.jpg -r 2000 -pix_fmt yuv420p -vsync 2    path\to\result\test.mp4

It works, but I am not able to see the video.
First of all I wonder if the code is right to convert jpg images to MP4 video with 2000 fps?
Secondly, what should I do with the attention note?
I really appreciate any help.


text:
Q: How to count how many line are between a specific part of a file? So, I'm trying to parse a Cucumber file (*.feature), in order to identify how many lines each Scenario has.
Example of file:

    Scenario: Add two numbers
       Given I have entered 50 into the calculator
       And I have entered 70 into the calculator
       When I press add
       Then the result should be 120 on the screen

    Scenario: Add many numbers
       Given I have entered 50 into the calculator
       And I have entered 20 into the calculator
       And I have entered 20 into the calculator
       And I have entered 30 into the calculator
       When I press add
       Then the result should be 120 on the screen

So, I'm expecting to parse this file and get results like:
Scenario: Add two numbers ---> it has 4 lines!
Scenario: Add many numbers ---> it has 6 lines!
What's the best approach to do that?

A: Why don't you start simple? Like @FeRtoll suggested, going line by line might be the easiest solution. Something as simple as the following might be what you are looking for :
scenario  = nil
scenarios = Hash.new{ |h,k| h[k] = 0 }

File.open("file_or_argv[0]_or_whatever.features").each do |line|
  next if line.strip.empty?

  if line[/^Scenario/]
    scenario = line
  else
    scenarios[scenario] += 1
  end
end

p scenarios

Output :
{"Scenario: Add two numbers \n"=>4, "Scenario: Add many numbers\n"=>6}

A: Enumerable#slice_before is pretty much tailor-made for this.
File.open('your cuke scenario') do |f|
  f.slice_before(/^\s*Scenario:/) do |scenario|
    title = scenario.shift.chomp
    ct = scenario.map(&:strip).reject(&:empty?).size
    puts "#{title} --> has #{ct} lines"
  end
end

A: FeRtoll suggested a good approach: accumulating by section.  The simplest way to parse it for me was to scrub out parts that I can ignore (i.e. comments) and then split into sections:
file = ARGV[0] or raise "Please supply a file name to parse"

def preprocess file
  data = File.read(file)
  data.gsub! /#.+$/, ''    # strip (ignore) comments
  data.gsub! /@.+$/, ''    # strip (ignore) tags
  data.gsub! /[ \t]+$/, '' # trim trailing whitespace
  data.gsub! /^[ \t]+/, '' # trim leading whitespace
  data.split /\n\n+/       # multiple blanks separate sections
end

sections = {
  :scenarios    => [],
  :background   => nil,
  :feature      => nil,
  :examples     => nil
}

parts = preprocess file

parts.each do |part|
  first_line, *lines = part.split /\n/

  if first_line.include? "Scenario:"
    sections[:scenarios] << {
      :name  => first_line.strip,
      :lines => lines
    }
  end

  if first_line.include? "Feature:"
    sections[:feature] = {
      :name  => first_line.strip,
      :lines => lines
    }
  end

  if first_line.include? "Background:"
    sections[:background] = {
      :name  => first_line.strip,
      :lines => lines
    }
  end
  if first_line.include? "Examples:"
    sections[:examples] = {
      :name  => first_line.strip,
      :lines => lines
    }
  end
end

if sections[:feature]
  puts "Feature has #{sections[:feature][:lines].size} lines."
end

if sections[:background]
  puts "Background has #{sections[:background][:lines].size} steps."
end

puts "There are #{sections[:scenarios].size} scenarios:"
sections[:scenarios].each do |scenario|
  puts "  #{scenario[:name]} has #{scenario[:lines].size} steps"
end

if sections[:examples]
  puts "Examples has #{sections[:examples][:lines].size} lines."
end

HTH

A: This is the current piece of code I'm working on (based on Kyle Burton approach):
def get_scenarios_info
    @scenarios_info = [:scenario_name => "", :quantity_of_steps => []]
    @all_files.each do |file|
        line_counter = 0
        File.open(file).each_line do |line|
            line.chomp!
            next if line.empty?
            line_counter = line_counter + 1
            if line.include? "Scenario:"
                @scenarios_info << {:scenario_name => line, :scenario_line => line_counter, :feature_file => file, :quantity_of_steps => []}
                next
            end
            @scenarios_info.last[:quantity_of_steps] << line
        end
    end
    #TODO: fix me here!
    @scenarios_info.each do |scenario|
        if scenario[:scenario_name] == ""
            @scenarios_info.delete(scenario)
        end
        scenario[:quantity_of_steps] = scenario[:quantity_of_steps].size
    end
    puts @scenarios_info
end


text:
Q: Sending one line of hash to method I have an array with words that I will use as keys. I iterate trough this array and put the words as keys and user input as value simplified like this:
input = Hash.new()
array.each do |a|

  input[a] = gets.strip
end

for example array ["one", "twoo", "three"]
and the user inputs first: three
I want to pass {"one" => "three"}
So the current key and value
Now I want to pass this "line" of the array to a method how do I do this ?

A: It is still unclear what you want to achieve. The way I see it, you can mean one of three things:

*

*"I want to pass the key and value after the user enters them to a method"
array.each do |key|
  input[key] = gets.strip
  my_method(key, input[key])
end

*A possible spin on that is "But I want to pass them as a single hash"
array.each do |key|
  input[key] = gets.strip
  my_method({key, input[key]})
end

*"I want to pass the entire hash after the user fills all the values"
array.each do |key|
  input[key] = gets.strip
end
my_method(input)

A: Just call that method and pass your "line":
input = Hash.new()

array.each do |a|
  input[a] = gets.strip

  # Send a line that user has inputed
  your_method(input[a])

  # Send key and the line that user has inputed
  your_method(a, input[a])
end

A: I got an impression that you are not trying to pass the entire hash at a time. If so, here is the one line answer
arr.each{|x| my_method({x => gets.strip})}

If I am wrong and you want to pass it at a time. Here is the one line answer
my_method(Hash[arr.zip(arr.map{gets.strip})])


text:
Q: Encrypt SSD before or after reinstalling Windows7 I format my computer's hard drive and re-install Windows every 3-6 months and it's time to do it again. A few months ago I installed Windows 7 on a brand new Intel 520 SSD.  At the time, I didn't set any hard drive password.  Now, I want to encrypt my hard drive.  If my assumption is correct, all I need to do is go to the BIOS settings when the computer boots and set an admin password and user password for the hard drive. Is this correct?
Also, should I set the hard drive passwords before or after I formatting the drive and re-install Window?

A: The Intel 520 always encrypts the data. The only difference between using the hard drive password or not is whether the encryption key itself is encrypted. So applying the hard drive password afterwards will cause the SSD to encrypt they encryption key used to encrypt your data, and so making you data inaccessible without the password. There is no need the reformat and reinstall.

A: Acording to this reference:

It is not a very well known fact, but all hard disks have a very
  strong hardware password capability build in. This password is usually
  stored both in a chip on the HD controller (the printed circuit board
  on the hard disk) and on the hard disk itself in a special hidden
  sector.
Setting this password will make the hard disk completely unusable to
  anyone that doesn't know it. And not only on your computer, but on any
  computer.
A lot of newer laptops will set the HD password together with the BIOS
  password, completely locking all the hardware.
The hard disk manufacturers are unable to unlock a password protected hard disk, as there aren't any "secret" master passwords
  build into the firmware. Even swapping the controller of the
  password-protected hard disk with exactly the same controller from an
  unprotected HD will not remove the protection on most disks, as the
  password (together with most of the firmware) is also stored on the
  hard disk itself.
The only way of retrieving any files from a password protected hard
  disk without knowing the password is to send it to a data recovery
  company for unlocking, but not all data recovery companies could or
  would unlock a password protected HD.
In this time of rising identity theft, protecting your personal data
  by locking your hard disk with a password is indeed a good idea. The
  downside is that when the HD eventually malfunctions it will be harder
  or even impossible to retrieve any files from it. So, the first rule
  of using a computer applies here in full strength – "Your data is only
  as good as your latest backup"!

This means that BIOS HDD password is not a encryption of your HDD(SSD on your case), but only a "lock". All your data inside your SSD will be protected due to the fact that the SSD reading is locked by the BIOS password, but the data by itself is not exactly encrypted. Assuming this, I can see no difference from inserting a BIOS password before or after Windows installation, both cases will work and both will lock SSD reading, but to make things easier I would set this BIOS password lock only after Windows installation. I mean, Windows installation will restart the machine some times to complete installation and everytime you must insert the BIOS password, this is the only reason to set it after.
There is also another reference here on SU about HDD BIOS password.


text:
Q: How to check the file path exists in sybase? How to check the filename exists in sybase Sql Anywhere11 and return error message if not in Sql Anywhere11?
I have a textbox and submit button in front end. So the user can enter the file path into the textbox and click submit.
The submit button call the procedure and i want to check in the beginning of the procedure weather the file exists or not and return some value if not exists.
Example:
D:/hello/world.csv is the path name.
So I need to check the D:/hello is a valid path and world.csv is exist in the specified path.
Thanks


text:
Q: How can I make a position:fixed image its own line/block? I have a menu button image placed below a logo div, and position:fixed to the right side of the viewport. My body text, however, also starts directly below the logo div, so if it's a large paragraph of text, it runs behind the image.
How can I get the fixed-position image to act as its own line/force a line break/work with display: block/otherwise push the text down so the text starts below the image?
I've tried using display: block with the image or image div, but I may be styling it wrong. Also, I clearly have no clue what I'm doing, so sorry about the mess!

    I'm some text!

And fiddle: http://jsfiddle.net/ylmk/B5LEk/2/

A: An element with position: fixed; or position: absolute; is taken out of the document flow and thus setting its display property to block won't do anything.
If you know the height of the image, I would simply using a margin or padding, e.g.:
header {
    padding-bottom: 2em;
}

Or:
header {
    margin-bottom: 2em;
}

Or, if you just have a sequence of
 elements after :
header + p { /* if you have a p after it */
    margin-top: 2em;
}


text:
Q: Overwrite CSS variables from Angular Material 15 The new Angular Material 15 has some "breaking" changes in regards of the colors and spacing. Therefore I need to overwrite the default values of the CSS variables. I define in my styles.scss
:root {
    --mdc-typography-button-letter-spacing: 'normal';
    --mdc-dialog-supporting-text-color: mat.get-color-from-palette($greyPalette, 900);
}

While the first variable is undefined and therefore the definition is taken the second variable has a value but is not overwritten.
So, how to set the variable properly?


text:
Q: Why cyclical learning rate has faster training time? In this article, Leslie implements an oscillating learning rate that when I train for 5 epochs using cyclical learning rate is faster than usual static learning rate for the same 5 epochs, why this happens?

A: The referred paper seems to answer your question, as it is the paper (as far as I know) that suggested using cyclical learning rate. Among other things, they say

The essence of this learning rate policy comes from the observation
  that increasing the learning rate might have a short term negative
  effect and yet achieve a longer term beneficial effect. This
  observation leads to the idea of letting the learning rate vary within
  a range of values rather than adopting a stepwise fixed or
  exponentially decreasing value.

So, as with many things in deep learning, they observed that it works. Everything beyond that would be post-hoc rationalizations why it could work. The paper does not describe any deeper theoretical background behind it, because there is none. It just works.
What the paper shows, is that when training the neural networks with cyclical learning rate, they converge faster, i.e. they need less epochs, or iterations, to achieve point where their performance does not really improve any further with more iterations. The paper does not claim that the time per iteration decreased.
Given your comment, you seem to be referring to this DataCamp tutorial, where the author claims that cyclical learning rate makes the code run faster (in terms of time, not epochs). First of all, this is a nonsense. The learning rate schedulers adjust learning rate before, or after each epoch, or step (doesn't matter that much, it is about implementation), so the additional few lines of code are run independently of the actual code. It is impossible that running few more lines of code could make the overall code run faster, it should run slightly slower (by negligible amount of time in this case). To prove the claim, the author uses code example with a bug, where he use different batch sizes (by 10x) for both conditions, what obviously has an impact on the run time.


text:
Q: Finding Occurrence of numbers in a String Goal is to fetch numbers which are followed by RatesLowerBound as variable rates and numbers which are alone fetch them as fixed rates.
Input String :- 'Basis(DataKeyBasisAmount(basisProperty=INPUT_EPSO_PAYMENT_AMOUNT)) [+0.05] RateLowerBound(value=2, inclusive=false) | [+0.07] RateLowerBound(value=5, inclusive=false) | [+0.10] RateLowerBound(value=20, inclusive=false) | [+0.35]'
Expected Output :- Var_Rate_1, Var_Rate_2, Var_Rate_3 , Fixed Rate
                     +0,05       +0.07       +0.10        +0.35

Tried the below sql code to fetch the results. It's giving expected output
SELECT Col1,
        REPLACE(REGEXP_SUBSTR (Col1,'\\[[^]]*',1,1),'[','') AS Var_Rate_1
        ,REPLACE(REGEXP_SUBSTR (Col1,'\\[[^]]*',1,2),'[','') AS Var_Rate_1
        ,REPLACE(REGEXP_SUBSTR (Col1,'\\[[^]]*',1,3),'[','') AS Var_Rate_1
        ,REPLACE(REGEXP_SUBSTR (Col1,'\\[[^]]*',1,4),'[','') AS Fixed_Rate_1
FROM (SELECT 'Basis(DataKeyBasisAmount(basisProperty=INPUT_EPSO_PAYMENT_AMOUNT)) [+0.05] RateLowerBound(value=2, inclusive=false) | [+0.07] RateLowerBound(value=5, inclusive=false) | [+0.10] RateLowerBound(value=20, inclusive=false) | [+0.35]' AS Col1);

But the problem is that order of fixed rates and variable rates can change in input string. For Example :- In the example string Fixed Rate is appearing in last but in other string it can appear as first element. So it's making difficult to tag to based on position.

A: I believe this does what you want:
SELECT LEFT(REGEXP_SUBSTR(Col1, '.{6} RateLowerBound', 1, 1), 5) AS Var_Rate_1,
       LEFT(REGEXP_SUBSTR(Col1, '.{6} RateLowerBound', 1, 2), 5) AS Var_Rate_2,
       LEFT(REGEXP_SUBSTR(Col1, '.{6} RateLowerBound', 1, 3), 5) AS Var_Rate_3,
       LEFT(REGEXP_SUBSTR(Col1, '.{6} RateLowerBound', 1, 4), 5) AS Var_Rate_4


text:
Q: Visualizations of JSON objects (Associative Arrays) I want to display JavaScript objects (JSON), or more generally associative arrays (hash, map). There is no problem with flat ones, these are simple tables. But it becomes problematic with arrays, and deeply nested objects.
Are there good libraries to visualize this? There are two options I see here

*

*Visualize as a nested table
This here is good example, I like it a lot, but apparently no library structure

*An associative array is a tree, so maybe reduce the problem to visualizing a tree.

A: I know theJIT - JavaScript InfoVis Toolkit - is a js library which can display tree (spacetree layout) graph structures from JSON data.
D3.js is another, it has tree layout js which can handle JSON data. There's this StackOverflow Question.
I've never tried any of them.

A: If this is for debugging from the backend I would highly recommend:
JSON View Chrome Extension
If however this is for Javascript debugging:
console.dir(myJSONObj);

console.dir works better for objs than console.log.


text:
Q: Restrict acces in DTO class for fields and return different value I'm implementing authorization in my Spring Boot application. And I want to apply authorization to dto's.
See the class below
public class ExampleDTO{
    private String phoneNumber; // want to restrict acces on this field.
}

E.g.
User A with permission A can see phoneNumber 123456789
User B with permission B can see phoneNumber 123456***
A solutions can be something like this:
public void setPhoneNumber(String iban) {
    if (Service.checkPermission("A")) {
        this.phoneNumber= 123456789;
    } else if (Service.checkPermission("B")) {
        this.phoneNumber= "123456***";
    } else {
        this.phoneNumber= "*********";
    }
}

But this is against the OOP principle.
Also I can do this in a service:
public ExampleDTO getExampleDto(String iban) {
    if (checkPermission("A")) {
        return ExampleDtoA;
    } else if (checkPermission("B")) {
        return ExampleDtoB;
    } else {
        return ExampleDtoC;
    }
}

But this will allow code duplication;
So does one of you have a better solution?

A: One way to go is to use a builder to build ExampleDto. Something like this:
public class ExampleDTOBuilder {

    public enum PhonePermission { A, B, NONE };

    private String phoneNumber;
    private PhonePermission phonePermission = PhonePermission.NONE;

    public ExampleDTOBuilder setPhoneNumber( String phoneNumber ) {
        this.phoneNumber = phoneNumber;
        return this;
    }

    public ExampleDTOBuilder setPermission(PhonePermission phonePermission) {
        this.phonePermission = phonePermission;
        return this;
    }

    public ExampleDTO build() {
        ExampleDTO dto = new ExampleDTO();

        switch (this.phonePermission) {
        case A:
            dto.setPhoneNumber(this.phoneNumber);
            break;
        case B:
            dto.setPhoneNumber(getMaskedPhoneNumber(this.phoneNumber));
        default:
            dto.setPhoneNumber("********");
            break;
        }

        return dto;
    }

    private String getMaskedPhoneNumber(String phoneNumber) {
        return "123***"; // do your masking
    }
}

Use:
ExampleDTO dto = new ExampleDTOBuilder()
        .setPermission(PhonePermission.A)
        .setPhoneNumber("123456")
        .build();

More details about the Builder pattern can be found here: https://en.wikipedia.org/wiki/Builder_pattern

A: I am assuming that you are saving these phone numbers in a database and that you want to persist the real phone numbers, but return different values based on permissions.
If this is the case, then you should not alter the setPhoneNumber method of the DTO as this could put the following phone number values into your DB: 123456***, *********.
You can encapsulate the logic in a converter between your entity and dto layer
public class ExampleService {
    ExampleDto getExample(String iban) {
        // Get entity from your DB
        ExampleEntity entity = entityRepository.getEntity(iban);
        return converter.convert(entity);
    }
}

public class Converter {
    public ExampleDto convert(ExampleEntity entity) {
        ExampleDto dto = new ExampleDto();
        if (checkPermission("A"))
            dto.setPhoneNumber(entity.getPhoneNumber());
        else if (checkPermission("B"))
            dto.setPhoneNumber(entity.getPhoneNumberPartialMasked();
        else
            dto.setPhoneNumber(entity.getPhoneNumberMasked());
        return dto;
    }
}

If you are using the spring framework, then you can see the following classes: org.springframework.core.convert.converter.Converter and org.springframework.core.convert.ConversionService. There are lots of examples out there on how to use these.


text:
Q: Impala null management: NULL DEFINED AS not working I'm facing a problem with null values and Impala. I created a table like this one:
 create table null_test (
  id int,
  val varchar(50)
 )
 row format delimited fields terminated by ','
 null defined as 'null'
 stored as textfile
 location '/tmp/test_null'

and I put there a file containing
1,null
2,foo
3,null

what happens is that Hive is working as expected and it is showing me the NULL values properly, instead Impala shows as values for the id 1 and 3 the string 'null'.
Is there any way to fix this behavior from Impala? How should I say to it how NULL values are represented?
Thank you!

A: It turned out that Impala doesn't manage NULL definition different from \N, i.e. if you want a value to be considered as  NULL by Impala you have to put \N, regardless of any property you set.


text:
Q: Send thread to background I am trying to implement a music player.
I wrote a class which extends from Thread and overwrote its Start()-Method to play a random song.
Playing a song works, but I want to send that thread to the background, which doesn't work:
File file = new File("song.mp3");
PlayEngine plengine = new PlayEngine(); //This class extends from Thread

plengine.Play(file); //This just sets the file to play in a variable
plengine.Start(); //And this finally plays the file itself

System.out.println("Next task:"); // I don't get to this point. Only when the song has finished.

As you can see in the code above, I'd like to go to the printed line right after launching the thread.

A: It is not recommended to extend Thread - Have your PlayEngine implement Runnable instead, and override the run method:
class PlayEngine implements Runnable {
    private final File file;

    PlayEngine(File file) {
        this.file = file;
    }

    @Override
    public void run() {
        //do your stuff here
        play(file);
    }
}

Then start the tread with:
PlayEngine plengine = new PlayEngine(file);
Thread t = new Thread(plengine);
t.start();
System.out.println("Next task:");

and Next task should print immediately. In your example, you seem to be calling the long running method play in the main thread, which explains why it does not return immediately.

A:
overwrote its Start()

I suspect you overriden Thread.start() which will never work. Either override Thread.run() or supply your own instance of Runnable to thread.

A: I think you should pring the log PlayEngine's run method very first. Moreover It appears you have written the playback code in start method(which runs in main thread) instead of run method. To get the playback done in background put the code in start in run method by overriding that.


text:
Q: How to melt a dataframe into a long form? I have the following dataframe
recycling 1 metric tonne (1000 kilogram) per waste type  Unnamed: 1 Unnamed: 2     Unnamed: 3       Unnamed: 4      Unnamed: 5
0    1 barrel oil is approximately 159 litres of oil       NaN          NaN            NaN              NaN             NaN
1                NaN                                       NaN          NaN            NaN              NaN             NaN
2                material                                  Plastic    Glass     Ferrous Metal     Non-Ferrous Metal     Paper
3               energy_saved                               5774 Kwh   42 Kwh         642 Kwh          14000 Kwh        4000 kWh
4               crude_oil saved                            16 barrels   NaN        1.8 barrels        40 barrels      1.7 barrels

For reference look at the image:

What I want to do is to get the rows 2, 3, 4 into cols in a new dataframe. It should be looking some like this..
  material   energy_saved   crude_oil saved
  plastic     5774Kwh         16 barrels
  Glass        42 Kwh          NaN
  ...           ...            ...

I tried using .melt but it was not working.
If you notice, the col name and its values are in a single row. I just want them to be in a new data frame as col and value.

A: IIUC, is it just:
out = df.loc[[2,3,4],:].T.reset_index(drop=True)