Programs & Examples On #Netmon

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

How to turn on line numbers in IDLE?

Line numbers were added to the IDLE editor two days ago and will appear in the upcoming 3.8.0a3 and later 3.7.5. For new windows, they are off by default, but this can be reversed on the Setting dialog, General tab, Editor section. For existing windows, there is a new Show (Hide) Line Numbers entry on the Options menu. There is currently no hotkey. One can select a line or bloc of lines by clicking on a line or clicking and dragging.

Some people may have missed Edit / Go to Line. The right-click context menu Goto File/Line works on grep (Find in Files) output as well as on trackbacks.

Execute function after Ajax call is complete

Try this code:

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
     url: 'api.php',                        
     data: 'id1='+q+'',                                                         
     dataType: 'json',
     async:false,                    
     success: function(data)          
     {   
        id = data[0];              
        vname = data[1];
     },
    complete: function (data) {
      printWithAjax(); 
     }
    });

  }//end of the for statement
  }//end of ajax call function

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.

How to sort a dataframe by multiple column(s)

You can use the order() function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:

R> dd[with(dd, order(-z, b)), ]
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1

Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order() function:

R> dd[order(-dd[,4], dd[,1]), ]
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1
R> 

rather than using the name of the column (and with() for easier/more direct access).

Where to put a textfile I want to use in eclipse?

Depending on your Java class package name, you're probably 4 or 5 levels down the directory structure.

If your Java class package is, for example, com.stackoverflow.project, then your class is located at src/com/stackoverflow/project.

You can either move up the directory structure with multiple ../, or you can move the text file to the same package as your class. It would be easier to move the text file.

Why did I get the compile error "Use of unassigned local variable"?

The default value table only applies to initializing a variable.

Per the linked page, the following two methods of initialization are equivalent...

int x = 0;
int x = new int();

In your code, you merely defined the variable, but never initialized the object.

How do I reverse an int array in Java?

It is most efficient to simply iterate the array backwards.

I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

Add http:// in front of url

Incorrect

<a href="www.example.com">www.example.com</span></p>

Correct

<a href="http://www.example.com">www.example.com</span></p>

How do I link to Google Maps with a particular longitude and latitude?

This works too:

https://www.google.pl/maps/@<lat>,<lon>,<zoom>z

Example.

With pointer:

https://www.google.com/maps/place/<lat>,<lon>/@<lat>,<lon>,<zoom>z

Example.

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Try this:

To accept theirs changes: git merge --strategy-option theirs

To accept yours: git merge --strategy-option ours

Convert NaN to 0 in javascript

You can do this:

a = a || 0

...which will convert a from any "falsey" value to 0.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )

Or this if you prefer:

a = a ? a : 0;

...which will have the same effect as above.


If the intent was to test for more than just NaN, then you can do the same, but do a toNumber conversion first.

a = +a || 0

This uses the unary + operator to try to convert a to a number. This has the added benefit of converting things like numeric strings '123' to a number.

The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:

+['123']  // 123

Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.

Pointer to 2D arrays in C

Ok, this is actually four different question. I'll address them one by one:

are both equals for the compiler? (speed, perf...)

Yes. The pointer dereferenciation and decay from type int (*)[100][280] to int (*)[280] is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.

is one of these solutions eating more memory than the other?

As a corollary to my first answer, no.

what is the more frequently used by developers?

Definitely the variant without the extra (*pointer) dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.

what is the best way, the 1st or the 2nd?

That depends on what you optimize for:

  • Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.

  • If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *. Having no array dimension there will feel weird to most programmers.

How can I read a text file in Android?

First you store your text file in to raw folder.

private void loadWords() throws IOException {
    Log.d(TAG, "Loading words...");
    final Resources resources = mHelperContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] strings = TextUtils.split(line, "-");
            if (strings.length < 2)
                continue;
            long id = addWord(strings[0].trim(), strings[1].trim());
            if (id < 0) {
                Log.e(TAG, "unable to add word: " + strings[0].trim());
            }
        }
    } finally {
        reader.close();
    }
    Log.d(TAG, "DONE loading words.");
}

How can I build for release/distribution on the Xcode 4?

You can use command line tool to build the release version. Next to your project folder, i.e.

$ ls
...
Foo.xcodeproj
...

Type the following build command:

$ xcodebuild -configuration Release

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

How do I get a HttpServletRequest in my spring beans?

If FlexContext is not available:

Solution 1: inside method (>= Spring 2.0 required)

HttpServletRequest request = 
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

@Autowired
private HttpServletRequest request;

Styling of Select2 dropdown select boxes

This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:

.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
    border-color: transparent transparent #fff transparent !important;
  }
  .select2-container--default .select2-selection--single .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent !important;
  }

Read Variable from Web.Config

Ryan Farley has a great post about this in his blog, including all the reasons why not to write back into web.config files: Writing to Your .NET Application's Config File

Unable to execute dex: Multiple dex files define

This problem occurs when a same library is added into your project multiple times. If you haven't added the library multiple times intentionaly, check out the dependency/private libraries of the libraries you have added in your project, most probably they have already included a library which is causing this conflict.

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

How do I declare class-level properties in Objective-C?

As seen on WWDC 2016/XCode 8 (what's new in LLVM session @5:05). Class properties can be declared as follows

@interface MyType : NSObject
@property (class) NSString *someString;
@end

NSLog(@"format string %@", MyType.someString);

Note that class properties are never synthesized

@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end

Pass data from Activity to Service using an Intent

If you are using kotlin you can try the following code,

In the sending activity,

  val intent = Intent(context, RecorderService::class.java);
  intent.putExtra("filename", filename);
  context.startService(intent)

In the service,

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)

    if (intent != null && intent.extras != null)
       val filename = intent.getStringExtra("filename")

}

Convert byte to string in Java

This is my version:

public String convertBytestoString(InputStream inputStream)
{
    int bytes;
    byte[] buffer = new byte[1024];

    bytes = inputStream.read(buffer);
    String stringData = new String(buffer,0,bytes);

    return stringData;

}

Styling the last td in a table with css

you could use the last-child psuedo class

table tr td:last-child {
    border: none;
}

This will style the last td only. It's not fully supported yet so it may be unsuitable

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Close Android Application

android.os.Process.killProcess(android.os.Process.myPid());

This code kill the process from OS Using this code disturb the OS. So I would recommend you to use the below code

this.finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

set column width of a gridview in asp.net

You need to convert the column into a 'TemplateField'.

In Designer View, click the smart tag of the GridView, select-> 'Edit columns'. Select your column you wish to modify and press the hyperlink converting it to a template. See screenshot: Converting column to template.

Note: Modifying your datasource might regenerate the columns again, so it might make changes to your template columns.

Ref: https://msdn.microsoft.com/en-us/library/bb288032.aspx

Android: How to create a Dialog without a title?

you can remove title by

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

where dialog is name of my dialog .

How to deal with page breaks when printing a large HTML table

Well Guys... Most of the Solutions up here didn't worked for. So this is how things worked for me..

HTML

<table>
  <thead>
   <tr>
     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     .
     .
   </tr>
   <tr>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>
     .
     .
   <tr>
  </thead>
<tbody>

    //YOUR CODE

</tbody>
</table>

The first set of head is used as a dummy one so that there won't be a missing top border in 2nd head(i.e. original head) while page break.

Leaflet changing Marker color

1) Add the marker 2) find the backgroundcolor attribute for the css and change it. Here it is:
JS

var myIcon = L.divIcon({
      className: 'my-div-icon',
      iconSize: [5, 5]
    });
var marker = L.marker([50,-20], {icon: myIcon}).addTo(map);
    marker.valueOf()._icon.style.backgroundColor = 'green'; //or any color

How can I align text in columns using Console.WriteLine?

You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...

Mail multipart/alternative vs multipart/mixed

Use multipart/mixed with the first part as multipart/alternative and subsequent parts for the attachments. In turn, use text/plain and text/html parts within the multipart/alternative part.

A capable email client should then recognise the multipart/alternative part and display the text part or html part as necessary. It should also show all of the subsequent parts as attachment parts.

The important thing to note here is that, in multipart MIME messages, it is perfectly valid to have parts within parts. In theory, that nesting can extend to any depth. Any reasonably capable email client should then be able to recursively process all of the message parts.

Xcode 4 - "Archive" is greyed out?

As the other answers state, you need to select an active scheme to something that is not a simulator, i.e. a device that's connected to your mac.

If you have no device connected to the mac then selecting "Generic IOS Device" works also.

enter image description here

How do you reindex an array in PHP but with indexes starting from 1?

Why reindexing? Just add 1 to the index:

foreach ($array as $key => $val) {
    echo $key + 1, '<br>';
}

Edit   After the question has been clarified: You could use the array_values to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.

Why is AJAX returning HTTP status code 0?

I think I know what may cause this error.

In google chrome there is an in-built feature to prevent ddos attacks for google chrome extensions.

When ajax requests continuously return 500+ status errors, it starts to throttle the requests.

Hence it is possible to receive status 0 on following requests.

Do Git tags only apply to the current branch?

If you want to tag the branch you are in, then type:

git tag <tag>

and push the branch with:

git push origin --tags

What is a Sticky Broadcast?

sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

ASP.NET MVC - Getting QueryString values

You can always use Request.QueryString collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.

how to run python files in windows command prompt?

First go to the directory where your python script is present by using-

cd path/to/directory

then simply do:

python file_name.py

How to test that a registered variable is not empty?

when: myvar | default('', true) | trim != ''

I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.

Adding up BigDecimals using Streams

If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.

List<BigDecimal> list = mList(
        BigDecimal.valueOf(0.1),
        BigDecimal.valueOf(1.1),
        BigDecimal.valueOf(2.1),
        BigDecimal.valueOf(0.1));

BigDecimal sum =
        list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);

BigDecimalSummaryStatistics statistics =
        list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());

Note: I am a committer for Eclipse Collections.

In log4j, does checking isDebugEnabled before logging improve performance?

As of 2.x, Apache Log4j has this check built in, so having isDebugEnabled() isn't necessary anymore. Just do a debug() and the messages will be suppressed if not enabled.

How to avoid 'undefined index' errors?

Same idea as Michael Waterfall

From CodeIgniter

// Lets you determine whether an array index is set and whether it has a value.
// If the element is empty it returns FALSE (or whatever you specify as the default value.)
function element($item, $array, $default = FALSE)
{
    if ( ! isset($array[$item]) OR $array[$item] == "")
    {
        return $default;
    }

    return $array[$item];
}

How to change TextField's height and width?

You can try the margin property in the Container. Wrap the TextField inside a Container and adjust the margin property.

new Container(
  margin: const EdgeInsets.only(right: 10, left: 10),
  child: new TextField( 
    decoration: new InputDecoration(
      hintText: 'username',
      icon: new Icon(Icons.person)),
  )
),

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

Simple Pivot Table to Count Unique Values

You can use COUNTIFS for multiple criteria,

=1/COUNTIFS(A:A,A2,B:B,B2) and then drag down. You can put as many criteria as you want in there, but it tends to take a lot of time to process.

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

You have to change androidx.constraintlayout.widget.ConstraintLayout to RelativeLayout.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example

//In Model

public class MyModel
{  
   [Required]
    public string Name{ get; set; }
}

//In PartailView //PartailView.cshtml

@model MyModel

<div>
    <div>
      @Html.LabelFor(model=>model.Name)
    </div>
    <div>
        @Html.EditorFor(model=>model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>

In Index.cshtml view

@model MyModel
<div id="targetId">
    @{Html.RenderPartial("PartialView",Model)}
</div>

@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
     <div>
        <input type="submit" value="Add Unit" />
    </div>
}

In Controller

public ActionResult Index()
{
  return View(new MyModel());
}


public string AddName(MyModel model)
{
   string HtmlString = RenderPartialViewToString("PartailView",model);
   return HtmlString;
}


protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.

git - Your branch is ahead of 'origin/master' by 1 commit

git reset HEAD^

then the modified files should show up.

You could move the modified files into a new branch

use,

git checkout -b newbranch

git checkout commit -m "files modified"

git push origin newbranch

git checkout master

then you should be on a clean branch, and your changes should be stored in newbranch. You could later just merge this change into the master branch

How can I find out which server hosts LDAP on my windows domain?

If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

XAMPP permissions on Mac OS X?

if you use one line folder or file

chmod 755 $(find /yourfolder -type d)
chmod 644 $(find /yourfolder -type f)

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

This is working code

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            { 
                    DropDownList1.DataTextField = "user_name";
                    DropDownList1.DataValueField = "user_id";
                    DropDownList1.DataSource = getData();// get the data into the list you can set it
                    DropDownList1.DataBind();

    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
            }
        }

java.lang.OutOfMemoryError: GC overhead limit exceeded

The parallel collector will throw an OutOfMemoryError if too much time is being spent in garbage collection. In particular, if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

Why doesn't the Scanner class have a nextChar method?

To get a definitive reason, you'd need to ask the designer(s) of that API.

But one possible reason is that the intent of a (hypothetical) nextChar would not fit into the scanning model very well.

  • If nextChar() to behaved like read() on a Reader and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type> methods. These skip over delimiter characters before they attempt to parse a value.

  • If nextChar() to behaved like (say) nextInt then:

    • the delimiter skipping would be "unexpected" for some folks, and

    • there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char, or maybe even support escaping or something1.

No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.


1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

How can I write to the console in PHP?

Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}

Get the filename of a fileupload in a document through JavaScript

RaYell, You don't need to parse the value returned. document.getElementById("FileUpload1").value returns only the file name with extension. This was useful for me because I wanted to copy the name of the file to be uploaded to an input box called 'title'. In my application, the uploaded file is renamed to the index generated by the backend database and the title is stored in the database.

Understanding the set() function

As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted on the set:

>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

How can I pass a username/password in the header to a SOAP WCF Service

I added customBinding to the web.config.

<configuration>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="CustomSoapBinding">
          <security includeTimestamp="false"
                    authenticationMode="UserNameOverTransport"
                    defaultAlgorithmSuite="Basic256"
                    requireDerivedKeys="false"
                    messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
          </security>
          <textMessageEncoding messageVersion="Soap11"></textMessageEncoding>
          <httpsTransport maxReceivedMessageSize="2000000000"/>
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="https://test.com:443/services/testService"
                binding="customBinding"
                bindingConfiguration="CustomSoapBinding"
                contract="testService.test"
                name="test" />
    </client>
  </system.serviceModel>
  <startup>
    <supportedRuntime version="v4.0"
                      sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

After adding customBinding, I can pass username and password to client service like as follows:

service.ClientCridentials.UserName.UserName = "testUser";
service.ClientCridentials.UserName.Password = "testPass";

In this way you can pass username, password in the header to a SOAP WCF Service.

Pyspark: Exception: Java gateway process exited before sending the driver its port number

I got the same Exception: Java gateway process exited before sending the driver its port number in Cloudera VM when trying to start IPython with CSV support with a syntax error:

PYSPARK_DRIVER_PYTHON=ipython pyspark --packages com.databricks:spark-csv_2.10.1.4.0

will throw the error, while:

PYSPARK_DRIVER_PYTHON=ipython pyspark --packages com.databricks:spark-csv_2.10:1.4.0

will not.

The difference is in that last colon in the last (working) example, seperating the Scala version number from the package version number.

ZIP file content type for HTTP request

The standard MIME type for ZIP files is application/zip. The types for the files inside the ZIP does not matter for the MIME type.

As always, it ultimately depends on your server setup.

Objective-C: Reading a file line by line

I see a lot of these answers rely on reading the whole text file into memory instead of taking it one chunk at a time. Here's my solution in nice modern Swift, using FileHandle to keep memory impact low:

enum MyError {
    case invalidTextFormat
}

extension FileHandle {

    func readLine(maxLength: Int) throws -> String {

        // Read in a string of up to the maximum length
        let offset = offsetInFile
        let data = readData(ofLength: maxLength)
        guard let string = String(data: data, encoding: .utf8) else {
            throw MyError.invalidTextFormat
        }

        // Check for carriage returns; if none, this is the whole string
        let substring: String
        if let subindex = string.firstIndex(of: "\n") {
            substring = String(string[string.startIndex ... subindex])
        } else {
            substring = string
        }

        // Wind back to the correct offset so that we don't miss any lines
        guard let dataCount = substring.data(using: .utf8, allowLossyConversion: false)?.count else {
            throw MyError.invalidTextFormat
        }
        try seek(toOffset: offset + UInt64(dataCount))
        return substring
    }

}

Note that this preserves the carriage return at the end of the line, so depending on your needs you may want to adjust the code to remove it.

Usage: simply open a file handle to your target text file and call readLine with a suitable maximum length - 1024 is standard for plain text, but I left it open in case you know it will be shorter. Note that the command will not overflow the end of the file, so you may have to check manually that you've not reached it if you intend to parse the entire thing. Here's some sample code that shows how to open a file at myFileURL and read it line-by-line until the end.

do {
    let handle = try FileHandle(forReadingFrom: myFileURL)
    try handle.seekToEndOfFile()
    let eof = handle.offsetInFile
    try handle.seek(toFileOffset: 0)

    while handle.offsetInFile < eof {
        let line = try handle.readLine(maxLength: 1024)
        // Do something with the string here
    }
    try handle.close()
catch let error {
    print("Error reading file: \(error.localizedDescription)"
}

Locate the nginx.conf file my nginx is actually using

% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf

If nginx was run without the -c option, then you can use the -V option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:

--prefix=PATH                      set installation prefix
--sbin-path=PATH                   set nginx binary pathname
--conf-path=PATH                   set nginx.conf pathname

C# "must declare a body because it is not marked abstract, extern, or partial"

You need to provide a body for the get; portion as well as the set; portion of the property.

I suspect you want this to be:

private int _hour; // backing field
private int Hour
    {
        get { return _hour; }
        set
        {
            //make sure hour is positive
            if (value < MIN_HOUR)
            {
                _hour = 0;
                MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                //take the modulus to ensure always less than 24 hours
                //works even if the value is already within range, or value equal to 24
                _hour = value % MAX_HOUR;
            }
        }
    }

That being said, I'd also consider making this code simpler. It's probably is better to use exceptions rather than a MessageBox inside of your property setter for invalid input, as it won't tie you to a specific UI framework.

If that is inappropriate, I would recommend converting this to a method instead of using a property setter. This is especially true since properties have an implicit expectation of being "lightweight"- and displaying a MessageBox to the user really violates that expectation.

ng: command not found while creating new project using angular-cli

I've solved the same issue with adding an alias like:

alias ng="path-to-your-global-node-modules/angular-cli/bin/ng"

Angles between two n-dimensional vectors in Python

David Wolever's solution is good, but

If you want to have signed angles you have to determine if a given pair is right or left handed (see wiki for further info).

My solution for this is:

def unit_vector(vector):
    """ Returns the unit vector of the vector"""
    return vector / np.linalg.norm(vector)

def angle(vector1, vector2):
    """ Returns the angle in radians between given vectors"""
    v1_u = unit_vector(vector1)
    v2_u = unit_vector(vector2)
    minor = np.linalg.det(
        np.stack((v1_u[-2:], v2_u[-2:]))
    )
    if minor == 0:
        raise NotImplementedError('Too odd vectors =(')
    return np.sign(minor) * np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

It's not perfect because of this NotImplementedError but for my case it works well. This behaviour could be fixed (cause handness is determined for any given pair) but it takes more code that I want and have to write.

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

Set a border around a StackPanel.

May be it will helpful:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

My solution is

fig = plt.figure()
fig.add_subplot(1, 2, 1)   #top and bottom left
fig.add_subplot(2, 2, 2)   #top right
fig.add_subplot(2, 2, 4)   #bottom right 
plt.show()

2x2 grid with 1 and 3 merge

Sound effects in JavaScript / HTML5

WebAudio API by W3C

As of July 2012, the WebAudio API is now supported in Chrome, and at least partly supported in Firefox, and is slated to be added to IOS as of version 6.

Although it is robust enough to be used programatically for basic tasks, the Audio element was never meant to provide full audio support for games, etc. It was designed to allow a single piece of media to be embedded in a page, similar to an img tag. There are a lot of issues with trying to use the Audio tag for games:

  • Timing slips are common with Audio elements
  • You need an Audio element for each instance of a sound
  • Load events aren't totally reliable, yet
  • No common volume controls, no fading, no filters/effects

I used this Getting Started With WebAudio article to get started with the WebAudio API. The FieldRunners WebAudio Case Study is also a good read.

Regex to split a CSV

I'm late to the party, but the following is the Regular Expression I use:

(?:,"|^")(""|[\w\W]*?)(?=",|"$)|(?:,(?!")|^(?!"))([^,]*?)(?=$|,)|(\r\n|\n)

This pattern has three capturing groups:

  1. Contents of a quoted cell
  2. Contents of an unquoted cell
  3. A new line

This pattern handles all of the following:

  • Normal cell contents without any special features: one,2,three
  • Cell containing a double quote (" is escaped to ""): no quote,"a ""quoted"" thing",end
  • Cell contains a newline character: one,two\nthree,four
  • Normal cell contents which have an internal quote: one,two"three,four
  • Cell contains quotation mark followed by comma: one,"two ""three"", four",five

See this pattern in use.

If you have are using a more capable flavor of regex with named groups and lookbehinds, I prefer the following:

(?<quoted>(?<=,"|^")(?:""|[\w\W]*?)*(?=",|"$))|(?<normal>(?<=,(?!")|^(?!"))[^,]*?(?=(?<!")$|(?<!"),))|(?<eol>\r\n|\n)

See this pattern in use.

Edit

(?:^"|,")(""|[\w\W]*?)(?=",|"$)|(?:^(?!")|,(?!"))([^,]*?)(?=$|,)|(\r\n|\n)

This slightly modified pattern handles lines where the first column is empty as long as you are not using Javascript. For some reason Javascript will omit the second column with this pattern. I was unable to correctly handle this edge-case.

HashSet vs. List performance

You're looking at this wrong. Yes a linear search of a List will beat a HashSet for a small number of items. But the performance difference usually doesn't matter for collections that small. It's generally the large collections you have to worry about, and that's where you think in terms of Big-O. However, if you've measured a real bottleneck on HashSet performance, then you can try to create a hybrid List/HashSet, but you'll do that by conducting lots of empirical performance tests - not asking questions on SO.

Python TypeError must be str not int

print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

How to copy sheets to another workbook using vba?

Here is one you might like it uses the Windows FileDialog(msoFileDialogFilePicker) to browse to a closed workbook on your desktop, then copies all of the worksheets to your open workbook:

Sub CopyWorkBookFullv2()
Application.ScreenUpdating = False

Dim ws As Worksheet
Dim x As Integer
Dim closedBook As Workbook
Dim cell As Range
Dim numSheets As Integer
Dim LString As String
Dim LArray() As String
Dim dashpos As Long
Dim FileName As String

numSheets = 0

For Each ws In Application.ActiveWorkbook.Worksheets
    If ws.Name <> "Sheet1" Then
       Sheets.Add.Name = "Sheet1"
   End If
Next

Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
Dim MyString As String

fileExplorer.AllowMultiSelect = False

  With fileExplorer
     If .Show = -1 Then 'Any file is selected
     MyString = .SelectedItems.Item(1)

     Else ' else dialog is cancelled
        MsgBox "You have cancelled the dialogue"
        [filePath] = "" ' when cancelled set blank as file path.
        End If
    End With

    LString = Range("A1").Value
    dashpos = InStr(1, LString, "\") + 1
    LArray = Split(LString, "\")
    'MsgBox LArray(dashpos - 1)
    FileName = LArray(dashpos)

strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & FileName

Set closedBook = Workbooks.Open(strFileName)
closedBook.Application.ScreenUpdating = False
numSheets = closedBook.Sheets.Count

        For x = 1 To numSheets
            closedBook.Sheets(x).Copy After:=ThisWorkbook.Sheets(1)
        x = x + 1
                 If x = numSheets Then
                    GoTo 1000
                 End If
Next

1000

closedBook.Application.ScreenUpdating = True
closedBook.Close
Application.ScreenUpdating = True

End Sub

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

Git pull command from different user

Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:

  1. Your friend pushes his changes to GitHub:

    git push origin <branch>
    
  2. Clone the remote repository if you haven't already:

    git clone https://[email protected]/abc/theproject.git
    
  3. Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):

    git fetch origin
    git merge origin/<branch>
    

    Note that git pull is the same as doing the two steps above:

    git pull origin <branch>
    

See Also

jQuery: Setting select list 'selected' based on text, failing strangely

The following works for text entries both with and without spaces:

$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);

Foreach loop in java for a custom object list

Using can also use Java 8 stream API and do the same thing in one line.

If you want to print any specific property then use this syntax:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));

OR

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
    // here room is available
});

if you want to print all the properties of Java object then use this:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

How to use a different version of python during NPM install?

for quick one time use this works, npm install --python="c:\python27"

Change collations of all columns of all tables in SQL Server

Fixed length problem nvarchar and added NULL/NOT NULL

DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
DECLARE @is_Nullable bit;
DECLARE @null nvarchar(25);

SET @collate = 'Latin1_General_CI_AS';

DECLARE local_table_cursor CURSOR FOR

SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1

OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE local_change_cursor CURSOR FOR

    SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
        , c.name column_name
        , t.Name data_type
        , c.max_length
        , c.column_id
        , c.is_nullable
    FROM sys.columns c
    JOIN sys.types t ON c.system_type_id = t.system_type_id
    LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id = OBJECT_ID(@table)
    ORDER BY c.column_id

    OPEN local_change_cursor
    FETCH NEXT FROM local_change_cursor
    INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@max_length = -1) SET @max_length = 4000;
        set @null=' NOT NULL'
        if (@is_nullable = 1) Set @null=' NULL'
        if (@Data_type='nvarchar') set @max_length=cast(@max_length/2 as bigint)
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + rtrim(@column_name) + '] ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) +  ') COLLATE ' + @collate + @null
            PRINT @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR: Some index or contraint rely on the column ' + @column_name + '. No conversion possible.'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM local_change_cursor
        INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_Nullable

    END

    CLOSE local_change_cursor
    DEALLOCATE local_change_cursor

    FETCH NEXT FROM local_table_cursor
    INTO @table

END

CLOSE local_table_cursor
DEALLOCATE local_table_cursor

GO

How can I get the ID of an element using jQuery?

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

$("#test").get(0).id

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")

How do I run a Python program?

What I just did, to open a simple python script by double clicking. I just added a batch file to the directory containing the script:

@echo off
python exercise.py
pause>nul

(I have the python executable on my system path. If not one would need include its complete path of course.)

Then I just can double click on the batch file to run the script. The third line keeps the cmd window from being dismissed as soon as the script ends, so you can see the results. :) When you're done just close the command window.

How to browse localhost on Android device?

to access localhost on emulator: 10.0.2.2. However this may not always work for example if you have something other than a web server such as XMPP server.

assuming that you're on the same wireless network...

  1. find your local ip (should be something 192.168.1.x) - go to the command line and type 'ipconfig' to get this. where x is the assigned local ip of the server machine.

  2. use your local ip for your android device to connect to your localhost.

it worked for me.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I've resolved the issue, by going to setting and permalink, just choose post-name.

it should work and you'll see the exact page.. rather than dashboard/xampp page again

Best of Luck

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

Get environment value in controller

In config/app.php file make a instance of env variable like 'name' => env('APP_NAME', 'Laravel') & In your controller call it like config('app.name')

Run following commands php artisan config:cache php artisan cache:clear if it is not working.

String Resource new line /n not possible?

use a blackslash not a forwardslash. \n

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello\nWorld!</string>
</resources>

Also, if you plan on using the string as HTML, you can use &lt;br /&gt; for a line break(<br />)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello&lt;br /&gt;World!</string>
</resources>

What's the console.log() of java?

public class Console {

    public static void Log(Object obj){
        System.out.println(obj);
    }
}

to call and use as JavaScript just do this:

Console.Log (Object)

I think that's what you mean

Max or Default?

Sounds like a case for DefaultIfEmpty (untested code follows):

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).DefaultIfEmpty.Max

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

Oracle SELECT TOP 10 records

If you are using Oracle 12c, use:

FETCH NEXT N ROWS ONLY

SELECT DISTINCT 
  APP_ID, 
  NAME, 
  STORAGE_GB, 
  HISTORY_CREATED, 
  TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE  
  FROM HISTORY WHERE 
    STORAGE_GB IS NOT NULL AND 
      APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
  ORDER BY STORAGE_GB DESC
FETCH NEXT 10 ROWS ONLY

More info: http://docs.oracle.com/javadb/10.5.3.0/ref/rrefsqljoffsetfetch.html

Determining type of an object in ruby

I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".

So we might enjoy this.

https://www.youtube.com/watch?v=1l3U1X3z0CE

But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.

12345.class

'my string'.class

They may also have ancestors

Object.ancestors

They also have meta classes but I'll save you the details on that.

Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...

"The Ruby Object Model"

This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.

Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.

text blocks numbers

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

Another git process seems to be running in this repository

Had the same problem using SourceTree. But there were no any index.lock file on my host at all. I've found packed-refs.lock file, and after deleting it, the problem was solved.

Python Timezone conversion

For Python 3.2+ simple-date is a wrapper around pytz that tries to simplify things.

If you have a time then

SimpleDate(time).convert(tz="...")

may do what you want. But timezones are quite complex things, so it can get significantly more complicated - see the the docs.

Batch file to split .csv file

I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.

@echo off
setLocal EnableDelayedExpansion
GOTO checkvars

:checkvars
    IF "%1"=="" GOTO syntaxerror
    IF NOT "%1"=="-f"  GOTO syntaxerror
    IF %2=="" GOTO syntaxerror
    IF NOT EXIST %2 GOTO nofile
    IF "%3"=="" GOTO syntaxerror
    IF NOT "%3"=="-n" GOTO syntaxerror
    IF "%4"==""  GOTO syntaxerror
    set param=%4
    echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
        goto proceed
    ) || (
        echo %param% is NOT a valid number
        goto syntaxerror
    )

:proceed
    set limit=%4
    set file=%2
    set lineCounter=1+%limit%
    set filenameCounter=0

    set name=
    set extension=

    for %%a in (%file%) do (
        set "name=%%~na"
        set "extension=%%~xa"
    )

    for /f "usebackq tokens=*" %%a in (%file%) do (
        if !lineCounter! gtr !limit! (
            set splitFile=!name!_part!filenameCounter!!extension!
            set /a filenameCounter=!filenameCounter! + 1
            set lineCounter=1
            echo Created !splitFile!.
        )
        cls
        echo Adding Line !splitFile! - !lineCounter!
        echo %%a>> !splitFile!
        set /a lineCounter=!lineCounter! + 1
    )
    echo Done!
    goto end
:syntaxerror
    Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
    goto end
:nofile
    echo %2 does not exist
    goto end
:end

Convert a dta file to csv without Stata software

I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.

The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"

Running Jupyter via command line on Windows

I just installed JupyterLab on top of my Python 3.8/pip enabled Win10 machine, so I ran into these startup problem with windows. If everything is ok (check that you have PATH for Python, eg. C:\Users[Username]\AppData\Local\Programs\Python\Python38-32\Scripts) you simply run:

jupyter-lab.exe

and that's it.

Cheers

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Is there a list of Pytz Timezones?

They appear to be populated by the tz database time zones found here.

enter image description here

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

PDOException SQLSTATE[HY000] [2002] No such file or directory

I ran into this problem when running PHPUnit in Elixir/Gulp, and Homestead as my Vagrant enviroment.

In my case I edited the .env file from DB_HOST=localhost to DB_HOST=192.168.10.10 where 192.168.10.10 is the IP of my Vagrant/Homestead host.

How to export a mysql database using Command Prompt?

For windows OS :

When you get error 1064 mysql (42000) while trying to execute mysqldump command, exit from current terminal. And execute mysqldump command.

mysql>exit 
c:\xampp\mysql\bin>mysqldump -uroot -p --databases [database_name] > name_for_export_db.sql

Java : How to determine the correct charset encoding of a stream

Here are my favorites:

TikaEncodingDetector

Dependency:

<dependency>
  <groupId>org.apache.any23</groupId>
  <artifactId>apache-any23-encoding</artifactId>
  <version>1.1</version>
</dependency>

Sample:

public static Charset guessCharset(InputStream is) throws IOException {
  return Charset.forName(new TikaEncodingDetector().guessEncoding(is));    
}

GuessEncoding

Dependency:

<dependency>
  <groupId>org.codehaus.guessencoding</groupId>
  <artifactId>guessencoding</artifactId>
  <version>1.4</version>
  <type>jar</type>
</dependency>

Sample:

  public static Charset guessCharset2(File file) throws IOException {
    return CharsetToolkit.guessEncoding(file, 4096, StandardCharsets.UTF_8);
  }

How to run Java program in command prompt

All you need to do is:

  • Build the mainjava class using the class path if any (optional)

    javac *.java [ -cp "wb.jar;"]

  • Create Manifest.txt file with content is:

    Main-Class: mainjava

  • Package the jar file for mainjava class

    jar cfm mainjava.jar Manifest.txt *.class

Then you can run this .jar file from cmd with class path (optional) and put arguments for it.

java [-cp "wb.jar;"] mainjava arg0 arg1 

HTH.

What is the best way to give a C# auto-property an initial value?

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

How to check Elasticsearch cluster health?

If Elasticsearch cluster is not accessible (e.g. behind firewall), but Kibana is:

Kibana => DevTools => Console:

GET /_cluster/health 

enter image description here enter image description here

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

How can I check the extension of a file?

Use pathlib From Python3.4 onwards.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

Printing 1 to 1000 without loop or conditionals

Fun with function pointers (none of that new-fangled TMP needed):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>


#define MSB(typ) ((sizeof(typ) * CHAR_BIT) - 1)

void done(int x, int y);
void display(int x, int y);

void (*funcs[])(int,int)  = {
    done,
    display
};

void done(int x, int y)
{
    exit(0);
}

void display(int x, int limit)
{
    printf( "%d\n", x);
    funcs[(((unsigned int)(x-limit)) >> MSB(int)) & 1](x+1, limit);
}


int main()
{
    display(1, 1000);
    return 0;
}

As a side note: I took the prohibition against conditionals to extend to logical and relational operators as well. If you allow logical negation, the recursive call can be simplified to:

funcs[!!(limit-1)](x+1, limit-1);

MySQL - Cannot add or update a child row: a foreign key constraint fails

Since you haven't given table definitions, it's hard to guess. But it looks like you are attempting to modify the foreign key in the child table. AFAIK, this is illegal, you can modify it from the parent, but not the child table.

Consider this example:

CREATE TABLE parent (
  parent_id INT NOT NULL,
  parent_data int,

  PRIMARY KEY (parent_id)
) ENGINE=INNODB;

CREATE TABLE child1 (
  child1_id INT,
  child1_data INT,
  fk_parent_id INT,

  INDEX par_ind1 (fk_parent_id),

  FOREIGN KEY (fk_parent_id)
    REFERENCES parent(parent_id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=INNODB;

CREATE TABLE child2 (
  child2_id INT,
  child2_data INT,
  fk_parent_id INT,

  INDEX par_ind2 (fk_parent_id),

  FOREIGN KEY (fk_parent_id)
    REFERENCES parent(parent_id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=INNODB;

INSERT INTO parent
  (parent_id, parent_data)
  VALUES
  (1, 11),
  (2, 12);

INSERT INTO child1
  (child1_id, child1_data, fk_parent_id)
  VALUES
  (101, 1001, 1),
  (102, 1002, 1),
  (103, 1003, 1),
  (104, 1004, 2),
  (105, 1005, 2);

INSERT INTO child2
  (child2_id, child2_data, fk_parent_id)
  VALUES
  (106, 1006, 1),
  (107, 1007, 1),
  (108, 1008, 1),
  (109, 1009, 2),
  (110, 1010, 2);

Then this is allowed:

UPDATE parent
  SET parent_id = 3 WHERE parent_id = 2;

SELECT * FROM parent;
SELECT * FROM child1;
SELECT * FROM child2;

But this is not, because it modifies the parent fk from the child table:

UPDATE child1
  SET fk_parent_id = 4 WHERE fk_parent_id = 1;

It gets an error very similar to your error:

Cannot add or update a child row: a foreign key constraint fails (`db_2_b43a7`.`child1`, CONSTRAINT `child1_ibfk_1` FOREIGN KEY (`fk_parent_id`) REFERENCES `parent` (`parent_id`) ON DELETE CASCADE ON UPDATE CASCADE):

How do I read text from the clipboard?

Use Pythons library Clipboard

Its simply used like this:

import clipboard
clipboard.copy("this text is now in the clipboard")
print clipboard.paste()  

How do I check if a C++ string is an int?

Here is another solution.

try
{
  (void) std::stoi(myString); //cast to void to ignore the return value   
  //Success! myString contained an integer
} 
catch (const std::logic_error &e)
{   
  //Failure! myString did not contain an integer
}

Remove all special characters, punctuation and spaces from string

Shorter way :

import re
cleanString = re.sub('\W+','', string )

If you want spaces between words and numbers substitute '' with ' '

Update Eclipse with Android development tools v. 23

After trying the approaches in other answers without success, I just installed a new bundle from http://developer.android.com/sdk/installing/index.html?pkg=adt and that worked fine.

Do the following:

  1. As you don't want to re-download all the platforms again, copy the existing one from /OLD_ANDROID_SDK_PATH/sdk/platforms to /NEW_ANDROID_SDK_PATH/sdk/platforms.
  2. When opening the new Eclipse from the recent downloaded bundle, make sure you reuse the previous 'workspace' folder. That will ensure that all your previous settings will be remembered.
  3. After opening the new Eclipse on the previous workspace, please check if the used Android SDK is pointing to the new one (Eclipse preferences -> Android). It might be pointing to the old one, as you've reused the previews workspace settings.

With these steps, you should't have to reconfigure everything, and you won't need to spend time troubleshooting this BUG on this upgrade from Google Developers.

Good luck! ;-)

Troubleshooting BadImageFormatException

You can also get this exception when your application target .NET Framework 4.5 (for example) and you have the following app.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
    <supportedRuntime version="v4.0" />
  </startup>
</configuration>

When trying to launch the debug of the application you will get the BadImageFormatException.

Removing the line declaring the v2.0 version will clear the error.

I had this issue recently when I tried to change the target platform from an old .NET 2.0 project to .NET 4.5.

AngularJS dynamic routing

In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ... , and access it in your controller via $routeParams.

There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route

EDIT (for the edited question):

The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include> tag in it ($scope.myTemplateUrl would be created in the controller).

I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:

http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm

Select2 doesn't work when embedded in a bootstrap modal

Ok, I've got it to work.

change

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Panel</h3>
  </div>
  <div class="modal-body" style="max-height: 800px">

to

<div id="myModal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Panel</h3>
  </div>
  <div class="modal-body" style="max-height: 800px">

(remove tabindex="-1" from modal)

How do I build an import library (.lib) AND a DLL in Visual C++?

Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.

In the non-Express version of VS, the import libray name is specfied in the project settings here:

Configuration Properties/Linker/Advanced/Import Library

I assume it's the same in Express (if it even provides the ability to configure the name).

How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

How can I embed a YouTube video on GitHub wiki pages?

Markdown does not officially support video embeddings but you can embed raw HTML in it. I tested out with GitHub Pages and it works flawlessly.

  1. Go to the Video page on YouTube and click on the Share Button
  2. Choose Embed
  3. Copy and Paste the HTML snippet in your markdown

The snippet looks like:

    <iframe width="560" height="315"
src="https://www.youtube.com/embed/MUQfKFzIOeU" 
frameborder="0" 
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" 
allowfullscreen></iframe>

PS: You can check out the live preview here

Catch an exception thrown by an async void method

Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.

The code below does the following:

  • Create 4 tasks
  • Each task will asynchronously increment a number and return the incremented number
  • When the async result has arrived it is traced.

 

static TypeHashes _type = new TypeHashes(typeof(Program));        
private void Run()
{
    TracerConfig.Reset("debugoutput");

    using (Tracer t = new Tracer(_type, "Run"))
    {
        for (int i = 0; i < 4; i++)
        {
            DoSomeThingAsync(i);
        }
    }
    Application.Run();  // Start window message pump to prevent termination
}


private async void DoSomeThingAsync(int i)
{
    using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
    {
        t.Info("Hi in DoSomething {0}",i);
        try
        {
            int result = await Calculate(i);
            t.Info("Got async result: {0}", result);
        }
        catch (ArgumentException ex)
        {
            t.Error("Got argument exception: {0}", ex);
        }
    }
}

Task<int> Calculate(int i)
{
    var t = new Task<int>(() =>
    {
        using (Tracer t2 = new Tracer(_type, "Calculate"))
        {
            if( i % 2 == 0 )
                throw new ArgumentException(String.Format("Even argument {0}", i));
            return i++;
        }
    });
    t.Start();
    return t;
}

When you observe the traces

22:25:12.649  02172/02820 {          AsyncTest.Program.Run 
22:25:12.656  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.657  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0    
22:25:12.658  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.659  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.659  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1    
22:25:12.660  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3    
22:25:12.664  02172/02756          } AsyncTest.Program.Calculate Duration 4ms   
22:25:12.666  02172/02820          } AsyncTest.Program.Run Duration 17ms  ---- Run has completed. The async methods are now scheduled on different threads. 
22:25:12.667  02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1    
22:25:12.667  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 8ms    
22:25:12.667  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.665  02172/05220 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.668  02172/02756 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.724  02172/05220          } AsyncTest.Program.Calculate Duration 66ms      
22:25:12.724  02172/02756          } AsyncTest.Program.Calculate Duration 57ms      
22:25:12.725  02172/05220 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106    
22:25:12.725  02172/02756 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0      
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 70ms   
22:25:12.726  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   
22:25:12.726  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.726  02172/05220          } AsyncTest.Program.Calculate Duration 0ms   
22:25:12.726  02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3    
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   

You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.

The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.

Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.


You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.

Run C++ in command prompt - Windows

Open cmd and go In Directory where file is saved. Then, For compile, g++ FileName. cpp Or gcc FileName. cpp

For Run, FileName. exe

This Is For Compile & Run Program.

Make sure, gcc compiler installed in PC or Laptop. And also path variable must be set.

How to use the IEqualityComparer

Just code, with implementation of GetHashCode and NULL validation:

public class Class_reglementComparer : IEqualityComparer<Class_reglement>
{
    public bool Equals(Class_reglement x, Class_reglement y)
    {
        if (x is null || y is null))
            return false;

        return x.Numf == y.Numf;
    }

    public int GetHashCode(Class_reglement product)
    {
        //Check whether the object is null 
        if (product is null) return 0;

        //Get hash code for the Numf field if it is not null. 
        int hashNumf = product.hashNumf == null ? 0 : product.hashNumf.GetHashCode();

        return hashNumf;
    }
}

Example: list of Class_reglement distinct by Numf

List<Class_reglement> items = items.Distinct(new Class_reglementComparer());

How to iterate over the keys and values with ng-repeat in AngularJS?

A todo list example which loops over object by ng-repeat:

_x000D_
_x000D_
var app = angular.module('toDolistApp', []);_x000D_
app.controller('toDoListCntrl', function() {_x000D_
  var self = this;_x000D_
  self.toDoListItems = {};// []; //dont use square brackets if keys are string rather than numbers._x000D_
  self.doListCounter = 0;_x000D_
_x000D_
  self.addToDoList = function() {         _x000D_
    var newToDoItem = {};_x000D_
    newToDoItem.title     = self.toDoEntry;_x000D_
    newToDoItem.completed = false;     _x000D_
_x000D_
    var keyIs = "key_" + self.doListCounter++;       _x000D_
_x000D_
    self.toDoListItems[keyIs] = newToDoItem;     _x000D_
    self.toDoEntry = ""; //after adding the item make the input box blank._x000D_
  };_x000D_
});_x000D_
_x000D_
app.filter('propsCounter', function() {_x000D_
  return function(input) {_x000D_
    return Object.keys(input).length;_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="toDolistApp">    _x000D_
  <div ng-controller="toDoListCntrl as toDoListCntrlAs">_x000D_
    Total Items: {{toDoListCntrlAs.toDoListItems | propsCounter}}<br />_x000D_
    Enter todo Item:  <input type="text" ng-model="toDoListCntrlAs.toDoEntry"/>_x000D_
    <span>{{toDoListCntrlAs.toDoEntry}}</span>_x000D_
    <button ng-click="toDoListCntrlAs.addToDoList()">Add Item</button> <br/>_x000D_
    <div ng-repeat="(key, prop) in toDoListCntrlAs.toDoListItems"> _x000D_
      <span>{{$index+1}} : {{key}}   : Title = {{ prop.title}} : Status = {{ prop.completed}} </span>_x000D_
    </div>     _x000D_
  </div>    _x000D_
</body>
_x000D_
_x000D_
_x000D_

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

Replace image src location using CSS

You can use a background image

_x000D_
_x000D_
.application-title img {_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  box-sizing:border-box;_x000D_
  padding-left: 200px;_x000D_
  /*width of the image*/_x000D_
  background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
  <img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
_x000D_
_x000D_

pandas dataframe columns scaling with sklearn

Like this?

dfTest = pd.DataFrame({
           'A':[14.00,90.20,90.95,96.27,91.21],
           'B':[103.02,107.26,110.35,114.23,114.68], 
           'C':['big','small','big','small','small']
         })
dfTest[['A','B']] = dfTest[['A','B']].apply(
                           lambda x: MinMaxScaler().fit_transform(x))
dfTest

    A           B           C
0   0.000000    0.000000    big
1   0.926219    0.363636    small
2   0.935335    0.628645    big
3   1.000000    0.961407    small
4   0.938495    1.000000    small

How to combine two or more querysets in a Django view?

Related, for mixing querysets from the same model, or for similar fields from a few models, Starting with Django 1.11 a QuerySet.union() method is also available:

union()

union(*other_qs, all=False)

New in Django 1.11. Uses SQL’s UNION operator to combine the results of two or more QuerySets. For example:

>>> qs1.union(qs2, qs3)

The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.

union(), intersection(), and difference() return model instances of the type of the first QuerySet even if the arguments are QuerySets of other models. Passing different models works as long as the SELECT list is the same in all QuerySets (at least the types, the names don’t matter as long as the types in the same order).

In addition, only LIMIT, OFFSET, and ORDER BY (i.e. slicing and order_by()) are allowed on the resulting QuerySet. Further, databases place restrictions on what operations are allowed in the combined queries. For example, most databases don’t allow LIMIT or OFFSET in the combined queries.

What is the 'dynamic' type in C# 4.0 used for?

COM interop. Especially IUnknown. It was designed specially for it.

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

Instantiate and Present a viewController in Swift

guard let vc = storyboard?.instantiateViewController(withIdentifier: "add") else { return }
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true, completion: nil)

When is a language considered a scripting language?

I think Mr Roberto Ierusalimschy has a very good answer or the question in 'Programming in Lua':

However, the distinguishing feature of interpreted languages is not that they are not compiled, but that any compiler is part of the language runtime and that, therefore, it is possible (and easy) to execute code generated on the fly

Writing file to web server - ASP.NET

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

When to use the JavaScript MIME type application/javascript instead of text/javascript?

The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.

But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript" is no longer required.

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I would probably build the link manually, like this:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

How to add an item to a drop down list in ASP.NET?

Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
     <asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>

If you want to add it at a different index, maybe the last then try:

ListItem lst = new ListItem ( "Add New" , "0" );

DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Disable and later enable all table indexes in Oracle

Combining the two answers:

First create sql to make all index unusable:

alter session set skip_unusable_indexes = true;
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;

Do import...

select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;

Dictionary returning a default value if the key does not exist

I created a DefaultableDictionary to do exactly what you are asking for!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace DefaultableDictionary {
    public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
        private readonly IDictionary<TKey, TValue> dictionary;
        private readonly TValue defaultValue;

        public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
            this.dictionary = dictionary;
            this.defaultValue = defaultValue;
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
            return dictionary.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Add(KeyValuePair<TKey, TValue> item) {
            dictionary.Add(item);
        }

        public void Clear() {
            dictionary.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item) {
            return dictionary.Contains(item);
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
            dictionary.CopyTo(array, arrayIndex);
        }

        public bool Remove(KeyValuePair<TKey, TValue> item) {
            return dictionary.Remove(item);
        }

        public int Count {
            get { return dictionary.Count; }
        }

        public bool IsReadOnly {
            get { return dictionary.IsReadOnly; }
        }

        public bool ContainsKey(TKey key) {
            return dictionary.ContainsKey(key);
        }

        public void Add(TKey key, TValue value) {
            dictionary.Add(key, value);
        }

        public bool Remove(TKey key) {
            return dictionary.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value) {
            if (!dictionary.TryGetValue(key, out value)) {
                value = defaultValue;
            }

            return true;
        }

        public TValue this[TKey key] {
            get
            {
                try
                {
                    return dictionary[key];
                } catch (KeyNotFoundException) {
                    return defaultValue;
                }
            }

            set { dictionary[key] = value; }
        }

        public ICollection<TKey> Keys {
            get { return dictionary.Keys; }
        }

        public ICollection<TValue> Values {
            get
            {
                var values = new List<TValue>(dictionary.Values) {
                    defaultValue
                };
                return values;
            }
        }
    }

    public static class DefaultableDictionaryExtensions {
        public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
            return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
        }
    }
}

This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.

The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.

Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);

Blog post on the usage as well.

z-index issue with twitter bootstrap dropdown menu

I had the same problem, in my case because i forgot this in my NavBar style: overflow: hidden;

Double quotes within php script echo

if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets

echo "i need to open my lock with its: {$array['key']}";

Check if value exists in Postgres array

Simpler with the ANY construct:

SELECT value_variable = ANY ('{1,2,3}'::int[])

The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:

Important difference: Array operators (<@, @>, && et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY construct expects an element type as left operand and does not support these indices. Example:

None of this works for NULL elements. To test for NULL:

How does the Python's range function work?

range(x) returns a list of numbers from 0 to x - 1.

>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]

for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range(). i is used inside the body to refer to the “current” item of the list. In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.

How to get the file path from HTML input form in Firefox 3

One extremely ugly way to resolve this is have the user manually type the directory into a text box, and add this back to the front of the file value in the JavaScript.

Messy... but it depends on the level of user you are working with, and gets around the security issue.

<form>
    <input type="text" id="file_path" value="C:/" />
    <input type="file" id="file_name" />
    <input type="button" onclick="ajax_restore();" value="Restore Database" />
</form>

JavaScript

var str = document.getElementById('file_path').value;
var str = str + document.getElementById('file_name').value;

Disable single warning error

Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push), #pragma warning (disable) and a matching #pragma warning (pop), as shown here.

Although there are some other options, including #pramga warning (once).

The term "Add-Migration" is not recognized

It's so simple.

Just install Microsoft.EntityFrameworkCore.Tools package from nuget:

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.5

You can also use this link to install the latest version: Nuget package link

.NET CLI command:

dotnet add package Microsoft.EntityFrameworkCore.Tools

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

I think you can use CHECK constraint - it is exactly what it was invented for.

ALTER TABLE someTable 
ADD CONSTRAINT someField_check CHECK (ISNUMERIC(someField) = 1) ;

My previous answer (also right by may be a bit overkill):

I think the right way is to use INSTEAD OF trigger to prevent the wrong data from being inserted (rather than deleting it post-factum)

How to get am pm from the date time string using moment js

you will get the time without specifying the date format. convert the string to date using Date object

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');

working solution:

_x000D_
_x000D_
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

How to run eclipse in clean mode? what happens if we do so?

You can start Eclipse in clean mode from the command line:

eclipse -clean

Need help rounding to 2 decimal places

It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).

See the following link: MSDN on Math.Round

Here is the relevant quote:

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

SELECT last id, without INSERT

You can get maximum column value and increment it:

InnoDB uses the following algorithm to initialize the auto-increment counter for a table t that contains an AUTO_INCREMENT column named ai_col: After a server startup, for the first insert into a table t, InnoDB executes the equivalent of this statement:

SELECT MAX(ai_col) FROM t FOR UPDATE;

InnoDB increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, InnoDB uses the value 1.

Also you can use SHOW TABLE STATUS and its "Auto_increment" value.

Best way to do multi-row insert in Oracle?

Here is a very useful step by step guideline for insert multi rows in Oracle:

https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html

The last step:

INSERT ALL
/* Everyone is a person, so insert all rows into people */
WHEN 1=1 THEN
INTO people (person_id, given_name, family_name, title)
VALUES (id, given_name, family_name, title)
/* Only people with an admission date are patients */
WHEN admission_date IS NOT NULL THEN
INTO patients (patient_id, last_admission_date)
VALUES (id, admission_date)
/* Only people with a hired date are staff */
WHEN hired_date IS NOT NULL THEN
INTO staff (staff_id, hired_date)
VALUES (id, hired_date)
  WITH names AS (
    SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,
           NULL hired_date, DATE'2009-12-31' admission_date
    FROM   dual UNION ALL
    SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,
           NULL hired_date, DATE'2014-01-01' admission_date
    FROM   dual UNION ALL
    SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,
           NULL hired_date, DATE'2015-04-22' admission_date
    FROM   dual UNION ALL
    SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,
           DATE'2015-01-01' hired_date, NULL admission_date
    FROM   dual
  )
  SELECT * FROM names

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

Vue.js: Conditional class style binding

Why not pass an object to v-bind:class to dynamically toggle the class:

<div v-bind:class="{ disabled: order.cancelled_at }"></div>

This is what is recommended by the Vue docs.

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

Retrieve only the queried element in an object array in MongoDB collection

Use aggregation function and $project to get specific object field in document

db.getCollection('geolocations').aggregate([ { $project : { geolocation : 1} } ])

result:

{
    "_id" : ObjectId("5e3ee15968879c0d5942464b"),
    "geolocation" : [ 
        {
            "_id" : ObjectId("5e3ee3ee68879c0d5942465e"),
            "latitude" : 12.9718313,
            "longitude" : 77.593551,
            "country" : "India",
            "city" : "Chennai",
            "zipcode" : "560001",
            "streetName" : "Sidney Road",
            "countryCode" : "in",
            "ip" : "116.75.115.248",
            "date" : ISODate("2020-02-08T16:38:06.584Z")
        }
    ]
}

Go to beginning of line without opening new line in VI

Type "^". And get a good "Vi" tutorial :)

How can I generate a tsconfig.json file?

install TypeScript :

npm install typescript

add tsc script to package.json:

"scripts": {
  "tsc": "tsc"
 },

run this:

npx tsc --init

OSX -bash: composer: command not found

this wasted me a day or two. like why dont anybody say on tutorials that the command composer is not to be used without actually linking and stuff... I mean everyone is writing composer command like its the next step when we are not all 5 years experienced users to know these details.

cp composer.phar /usr/local/bin/composer

did it for me on ubuntu after getting stuck for 2 days

Integer to hex string in C++

Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

You can prepend the first << with << "0x" or whatever you like if you wish.

Other manips of interest are std::oct (octal) and std::dec (back to decimal).

One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
       << std::hex << your_int;

So finally, I'd suggest such a function:

template< typename T >
std::string int_to_hex( T i )
{
  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;
  return stream.str();
}

Could not find the main class, program will exit

I got this issue in opening JMeter 4.0. I fixed as below.

I have JRE 7 installed in Program Files (x86) folder and JDK 8 installed in Program files folder. So I just uninstalled JRE7 from machine. I just kept latest version of JDK. It fixed the problem.

Cannot create SSPI context

In case you are running a code not written in your computer, that runs in a computer used by your work peer, but not in yours, check the web.config. Maybe there is your colleague's name as userPrincipalName at some place that should be in blank. That happens automatically when we create a service reference to the project in VS.

decompiling DEX into Java sourcecode

This can be done in following five steps:

This gem does these things for you automatically even the installation of required tools

  1. convert apk file to zip
  2. unzip the file
  3. extract classes.dex from it
  4. use dex to jar to convert classes.dex into jar file
  5. use jadx gui to open the jar file as java source code

What is the simplest way to convert array to vector?

One simple way can be the use of assign() function that is pre-defined in vector class.

e.g.

array[5]={1,2,3,4,5};

vector<int> v;
v.assign(array, array+5); // 5 is size of array.

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

Proxy Basic Authentication in C#: HTTP 407 error

This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.

Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.

request.Proxy.Credentials = CredentialCache.DefaultCredentials;

Word wrap for a label in Windows Forms

From MSDN, Automatically Wrap Text in Label:

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing) 
            return;
        try {
            mGrowing = true;
            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height;
        }
        finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

Why would anybody use C over C++?

Long compile times can be annoying. With C++ you can have very long compile times (which means, of course, more time for Stack Overflow!).

What is the meaning of @_ in Perl?

You can also use shift for individual variables in most cases:

$var1 = shift;

This is a topic in which you should research further as Perl has a number of interesting ways of accessing outside information inside your sub routine.

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

I had the same issue after upgrading to macOS Catalina. This didn't work for me:

xcode-select --install

Downloading and installing Command Line Tools for Xcode 12 did it!

enter image description here

Date Format in Swift

Swift 3 with a Date extension

extension Date {
    func string(with format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

Then you can use it like so:

let date = Date()
date.string(with: "MMM dd, yyyy")

How do I adb pull ALL files of a folder present in SD Card

On Android 6 with ADB version 1.0.32, you have to put / behind the folder you want to copy. E.g adb pull "/sdcard/".

Convert Array to Object

With a function like this:

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    rv[i] = arr[i];
  return rv;
}

Your array already is more-or-less just an object, but arrays do have some "interesting" and special behavior with respect to integer-named properties. The above will give you a plain object.

edit oh also you might want to account for "holes" in the array:

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    if (arr[i] !== undefined) rv[i] = arr[i];
  return rv;
}

In modern JavaScript runtimes, you can use the .reduce() method:

var obj = arr.reduce(function(acc, cur, i) {
  acc[i] = cur;
  return acc;
}, {});

That one also avoids "holes" in the array, because that's how .reduce() works.

How can I get the console logs from the iOS Simulator?

If you are using Swift, remember that println will only print to the debug log (which appears in xCode's debug area). If you want to print to system.log, you have to use NSLog as in the old days.

Then you can view the simulator log via its menu, Debug > Open System Log... (cmd + /)

How to write the Fibonacci Sequence?

import time
start_time = time.time()



#recursive solution
def fib(x, y, upperLimit):
    return [x] + fib(y, (x+y), upperLimit) if x < upperLimit else [x]

#To test :

print(fib(0,1,40000000000000))
print("run time: " + str(time.time() - start_time))

Results

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853]

run time: 0.04298138618469238

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

/**
 * Navbar styling.
 */
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

http://lesscss.org

Executing an EXE file using a PowerShell script

  1. clone $args
  2. push your args in new array
  3. & $path $args

Demo:

$exePath = $env:NGINX_HOME + '/nginx.exe'
$myArgs = $args.Clone()

$myArgs += '-p'
$myArgs += $env:NGINX_HOME

& $exepath $myArgs

Pandas: Return Hour from Datetime Column Directly

Assuming timestamp is the index of the data frame, you can just do the following:

hours = sales.index.hour

If you want to add that to your sales data frame, just do:

import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)

Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:

hours = sales['date'].hour

Edit2: If you want to adjust a column in your data frame you have to include dt:

sales['datehour'] = sales['date'].dt.hour

How to Extract Year from DATE in POSTGRESQL

answer is;

select date_part('year', timestamp '2001-02-16 20:38:40') as year,
       date_part('month', timestamp '2001-02-16 20:38:40') as month,
       date_part('day', timestamp '2001-02-16 20:38:40') as day,
       date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
       date_part('minute', timestamp '2001-02-16 20:38:40') as minute

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();