Programs & Examples On #App offline.htm

ASP.NET 2.0 - How to use app_offline.htm

I ran into an issue very similar to the original question that took me a little while to resolve.

Just incase anyone else is working on an MVC application and finds their way into this thread, make sure that you have a wildcard mapping to the appropriate .Net aspnet_isapi.dll defined. As soon as I did this, my app_offline.htm started behaving as expected.


IIS 6 Configuration Steps

On IIS Application Properties, select virtual Directory tab.

Under Application Settings, click the Configuration button.

Under Wildcard application maps, click the Insert button.

Enter C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll, click OK.

What is the correct way to free memory in C#

As Brian points out the GC can collect anything that is unreachable including objects that are still in scope and even while instance methods of those objects are still executing. consider the following code:

class foo
{
    static int liveFooInstances;

    public foo()
    {
        Interlocked.Increment(ref foo.liveFooInstances);
    }

    public void TestMethod()
    {
        Console.WriteLine("entering method");
        while (Interlocked.CompareExchange(ref foo.liveFooInstances, 1, 1) == 1)
        {
            Console.WriteLine("running GC.Collect");
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        Console.WriteLine("exiting method");
    }

    ~foo()
    {
        Console.WriteLine("in ~foo");
        Interlocked.Decrement(ref foo.liveFooInstances);
    }

}

class Program
{

    static void Main(string[] args)
    {
        foo aFoo = new foo();
        aFoo.TestMethod();
        //Console.WriteLine(aFoo.ToString()); // if this line is uncommented TestMethod will never return
    }
}

if run with a debug build, with the debugger attached, or with the specified line uncommented TestMethod will never return. But running without a debugger attached TestMethod will return.

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

The Log class:

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Outside of Android, System.out.println(String msg) is used.

How to replace all special character into a string using C#

You can use a regular expresion to for example replace all non-alphanumeric characters with commas:

s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");

Note: The + after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

Opacity of background-color, but not the text

Relaxing your requirement to work on IE6 and legacy browsers you can use ::before and display: inline-block

div
{
  display: inline-block;
  position: relative;    
}
div::before
{
  content: "";
  display: block;
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  background:red;
  opacity: .2;
}

Demo at http://jsfiddle.net/KVyFH/172/ ?

It will work on any modern browser

CSS :not(:last-child):after selector

If it's a problem with the not selector, you can set all of them and override the last one

li:after
{
  content: ' |';
}
li:last-child:after
{
  content: '';
}

or if you can use before, no need for last-child

li+li:before
{
  content: '| ';
}

PHP Session data not being saved

Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out

Android Relative Layout Align Center

If you want to make it center then use android:layout_centerVertical="true" in the TextView.

What is the difference between ELF files and bin files?

some resources:

  1. ELF for the ARM architecture
    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
  2. ELF from wiki
    http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:

  arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]

or using fromELF utility(built in most IDEs such as ADS though):

 fromelf -bin -o [binary-output-file] [elf-input-file]

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

I came here on searching the error with my recyclerview but the solution didn't work (obviously). I have written the cause and the solution for it in case of recyclerview. Hope it helps someone.

The error is caused if in the onCreateViewHolder() the following method is followed:

layoutInflater = LayoutInflater.from(context);
return new VH(layoutInflater.inflate(R.layout.single_row, parent));

Instead it should be

return new VH(layoutInflater.inflate(R.layout.single_row, null));

Why are my CSS3 media queries not working on mobile devices?

Today I had similar situation. Media query did not work. After a while I found that space after 'and' was missing. Proper media query should look like this:

@media screen and (max-width: 1024px) {}

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

In .NET, which loop runs faster, 'for' or 'foreach'?

It probably depends on the type of collection you are enumerating and the implementation of its indexer. In general though, using foreach is likely to be a better approach.

Also, it'll work with any IEnumerable - not just things with indexers.

How to start an Android application from the command line?

adb shell
am start -n com.package.name/com.package.name.ActivityName

Or you can use this directly:

adb shell am start -n com.package.name/com.package.name.ActivityName

You can also specify actions to be filter by your intent-filters:

am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName

What are the date formats available in SimpleDateFormat class?

Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
       Date now = new Date();

       //This is just Date's toString method and doesn't involve SimpleDateFormat
       System.out.println("toString(): " + now);  // dow mon dd hh:mm:ss zzz yyyy
       //Shows  "Mon Oct 08 08:17:06 EDT 2012"

       SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
       System.out.println("Format 1:   " + dateFormatter.format(now));
       // Shows  "Mon, 2012-10-8 at 8:17:6 AM EDT"

       dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       System.out.println("Format 2:   " + dateFormatter.format(now));
       // Shows  "Mon 2012.10.08 at 08:17:06 AM EDT"

       dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
       System.out.println("Format 3:   " + dateFormatter.format(now));
       // Shows  "Monday, October 8, 2012"

       // SimpleDateFormat can be used to control the date/time display format:
       //   E (day of week): 3E or fewer (in text xxx), >3E (in full text)
       //   M (month): M (in number), MM (in number with leading zero)
       //              3M: (in text xxx), >3M: (in full text full)
       //   h (hour): h, hh (with leading zero)
       //   m (minute)
       //   s (second)
       //   a (AM/PM)
       //   H (hour in 0 to 23)
       //   z (time zone)
       //  (there may be more listed under the API - I didn't check)

   }

}

Good luck!

How can I find a file/directory that could be anywhere on linux command line?

To get rid of permission errors (and such), you can redirect stderr to nowhere

find / -name "something" 2>/dev/null

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

How do I create a GUI for a windows application using C++?

Avoid QT (for noobs) or any useless libraries (absurd for a such basic thing)

Just use the VS Win32 api Wizard, ad the button and text box...and that's all !

In 25 seconds !

The opposite of Intersect()

/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
    /// <summary>
    /// Returns list of items that are in initial but not in final list.
    /// </summary>
    /// <param name="listA"></param>
    /// <param name="listB"></param>
    /// <returns></returns>
    public static IEnumerable<string> NonIntersect(
        List<string> initial, List<string> final)
    {
        //subtracts the content of initial from final
        //assumes that final.length < initial.length
        return initial.Except(final);
    }

    /// <summary>
    /// Returns the symmetric difference between the two list.
    /// http://en.wikipedia.org/wiki/Symmetric_difference
    /// </summary>
    /// <param name="initial"></param>
    /// <param name="final"></param>
    /// <returns></returns>
    public static IEnumerable<string> SymmetricDifference(
        List<string> initial, List<string> final)
    {
        IEnumerable<string> setA = NonIntersect(final, initial);
        IEnumerable<string> setB = NonIntersect(initial, final);
        // sum and return the two set.
        return setA.Concat(setB);
    }
}

How to replace space with comma using sed?

On Linux use below to test (it would replace the whitespaces with comma)

 sed 's/\s/,/g' /tmp/test.txt | head

later you can take the output into the file using below command:

sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt

PS: test is the file which you want to use

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> 
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

Rename a column in MySQL

In mysql your query should be like

ALTER TABLE table_name change column_1 column_2 Data_Type;

you have written the query in Oracle.

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

What is Model in ModelAndView from Spring MVC?

new ModelAndView("welcomePage", "WelcomeMessage", message);

is shorthand for

ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);

Looking at the code above, you can see the view name is "welcomePage". Your ViewResolver (usually setup in .../WEB-INF/spring-servlet.xml) will translate this into a View. The last line of the code sets an attribute in your model (addObject("WelcomeMessage", message)). That's where the model comes into play.

Is there a .NET/C# wrapper for SQLite?

A barebones wrapper of the functions as provided by the sqlite library. Latest version supports functions provided sqlite library 3.7.10

SQLiteWrapper project

Populating a database in a Laravel migration file

This should do what you want.

public function up()
{
    DB::table('user')->insert(array('username'=>'dude', 'password'=>'z19pers!'));
}

Spring 3 RequestMapping: Get path value

private final static String MAPPING = "/foo/*";

@RequestMapping(value = MAPPING, method = RequestMethod.GET)
public @ResponseBody void foo(HttpServletRequest request, HttpServletResponse response) {
    final String mapping = getMapping("foo").replace("*", ""); 
    final String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    final String restOfPath = url.replace(mapping, "");
    System.out.println(restOfPath);
}

private String getMapping(String methodName) {
    Method methods[] = this.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName() == methodName) {
            String mapping[] = methods[i].getAnnotation(RequestMapping.class).value();
            if (mapping.length > 0) {
                return mapping[mapping.length - 1];
            }
        }
    }
    return null;
}

Print Html template in Angular 2 (ng-print in Angular 2)

That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:

<div id="print-section">
  // your html stuff that you want to print
</div>
<button (click)="print()">print</button>

and in your TS file :

print(): void {
    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
          <style>
          //........Customized style.......
          </style>
        </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
}

UPDATE:

You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.

How do you convert a C++ string to an int?

I have used something like the following in C++ code before:

#include <sstream>
int main()
{
    char* str = "1234";
    std::stringstream s_str( str );
    int i;
    s_str >> i;
}

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

C++ style cast from unsigned char * to const char *

Try reinterpret_cast

unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));

mysql said: Cannot connect: invalid settings. xampp

Best Way is reinstall if you have xampp/wamp/mamp or in linux uninstall and reinstall phpmyadmin by using apt-get

Iterating over a numpy array

see nditer

import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
    y += 3

Y == np.array([6, 7, 8, 9])

y = 3 would not work, use y *= 0 and y += 3 instead.

How do I set vertical space between list items?

HTML

<ul>
   <li>A</li>
   <li>B</li>
   <li>C</li>
   <li>D</li>
   <li>E</li>
</ul>

CSS

li:not(:last-child) {
    margin-bottom: 5px;
}

EDIT: If you don't use the special case for the last li element your list will have a small spacing afterwards which you can see here: http://jsfiddle.net/wQYw7/

Now compare that with my solution: http://jsfiddle.net/wQYw7/1/

Sure this doesn't work in older browsers but you can easily use js extensions which will enable this for older browsers.

WCF Exception: Could not find a base address that matches scheme http for the endpoint

I tried the binding according to the answer by @Szymon but It did not work for me. I tried basicHttpsBinding which is new in .net 4.5 and It solved the issue. Here is the complete configuration that works for me.

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpsBinding>
        <binding name="basicHttpsBindingForYourService">
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"/>
          </security>
        </binding>
      </basicHttpsBinding>
    </bindings>
    <services>
      <service name="YourServiceName">
        <endpoint address="" binding="basicHttpsBinding" bindingName="basicHttpsBindingForYourService" contract="YourContract" />
      </service>
    </services>   
</system.serviceModel>

FYI: My application's target framework is 4.5.1. IIS web site that I created to deploy this wcf service only has https binding enabled.

React JSX: selecting "selected" on selected <select> option

Use defaultValue to preselect the values for Select.

<Select defaultValue={[{ value: category.published, label: 'Publish' }]} options={statusOptions} onChange={handleStatusChange} />

Sort Go map values by keys

All of the answers here now contain the old behavior of maps. In Go 1.12+, you can just print a map value and it will be sorted by key automatically. This has been added because it allows the testing of map values easily.

func main() {
    m := map[int]int{3: 5, 2: 4, 1: 3}
    fmt.Println(m)

    // In Go 1.12+
    // Output: map[1:3 2:4 3:5]

    // Before Go 1.12 (the order was undefined)
    // map[3:5 2:4 1:3]
}

Maps are now printed in key-sorted order to ease testing. The ordering rules are:

  • When applicable, nil compares low
  • ints, floats, and strings order by <
  • NaN compares less than non-NaN floats
  • bool compares false before true
  • Complex compares real, then imaginary
  • Pointers compare by machine address
  • Channel values compare by machine address
  • Structs compare each field in turn
  • Arrays compare each element in turn
  • Interface values compare first by reflect.Type describing the concrete type and then by concrete value as described in the previous rules.

When printing maps, non-reflexive key values like NaN were previously displayed as <nil>. As of this release, the correct values are printed.

Read more here.

Specify JDK for Maven to use

I say you setup the JAVA_HOME environment variable like Pascal is saying: In Cygwin if you use bash as your shell should be:

export JAVA_HOME=/cygdrive/c/pathtothejdk

It never harms to also prepend the java bin directory path to the PATH environment variable with:

export PATH=${JAVA_HOME}/bin:${PATH}

Also add maven-enforce-plugin to make sure the right JDK is used. This is a good practice for your pom.

<build>
 <plugins>
   <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-enforcer-plugin</artifactId>
      <executions>
        <execution>
          <id>enforce-versions</id>
          <goals>
            <goal>enforce</goal>
          </goals>
          <configuration>
            <rules>
              <requireJavaVersion>
                <version>1.6</version>
              </requireJavaVersion>
            </rules>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Please, see Maven Enforcer plugin – Usage.

Set attribute without value

Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:

document.querySelector('#selector').toggleAttribute('data-something');

This will add the attribute in all lowercase without a value or remove it if it already exists on the element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute

Twitter bootstrap remote modal shows same content every time

For bootstrap 3 you should use:

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

how to create a cookie and add to http response from inside my service layer?

In Spring MVC you get the HtppServletResponce object by default .

   @RequestMapping("/myPath.htm")
    public ModelAndView add(HttpServletRequest request,
         HttpServletResponse response) throws Exception{
            //Do service call passing the response
    return new ModelAndView("CustomerAddView");
    }

//Service code
Cookie myCookie =
  new Cookie("name", "val");
  response.addCookie(myCookie);

The given key was not present in the dictionary. Which key?

string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"

With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');
    

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
    

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)

OR

  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

iOS detect if user is on an iPad

I found that some solution didn't work for me in the Simulator within Xcode. Instead, this works:

ObjC

NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;

if ([[deviceModel substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"iPad"]) {
    DebugLog(@"iPad");
} else {
    DebugLog(@"iPhone or iPod Touch");
}

Swift

if UIDevice.current.model.hasPrefix("iPad") {
    print("iPad")
} else {
    print("iPhone or iPod Touch")
}

Also in the 'Other Examples' in Xcode the device model comes back as 'iPad Simulator' so the above tweak should sort that out.

How do I get the App version and build number using Swift?

Update for Swift 5

here's a function i'm using to decide whether to show an "the app updated" page or not. It returns the build number, which i'm converting to an Int:

if let version: String = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
        guard let intVersion = Int(version) else { return }
        
        if UserDefaults.standard.integer(forKey: "lastVersion") < intVersion {
            print("need to show popup")
        } else {
            print("Don't need to show popup")
        }
        
        UserDefaults.standard.set(intVersion, forKey: "lastVersion")
    }

If never used before it will return 0 which is lower than the current build number. To not show such a screen to new users, just add the build number after the first login or when the on-boarding is complete.

How can I mix LaTeX in with Markdown?

What language are you using?

If you can use ruby, then maruku can be configured to process maths using various latex->MathML converters. Instiki uses this. It's also possible to extend PHPMarkdown to use itex2MML as well to convert maths. Basically, you insert extra steps in the Markdown engine at the appropriate points.

So with ruby and PHP, this is done. I guess these solutions could also be adapted to other languages - I've gotten the itex2MML extension to produce perl bindings as well.

How to set transparent background for Image Button in code?

DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button (or the generic view) will no more highlight at click!!!

I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view

Use this in the button specifications

android:background="?android:selectableItemBackground"

This requires API 11

Visual Studio 2017 - Git failed with a fatal error

After installing the last version of Git for Windows you must to open the configuration file to edit:

git config --global --edit

Click Insert, remove all the settings, click Esc, type :wq and, Enter to save.

Now you can clone the repository by Bash or IDE with a valid user.

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

Nested Recycler view height doesn't wrap its content

An alternative to extend LayoutManager can be just set the size of the view manually.

Number of items per row height (if all the items have the same height and the separator is included on the row)

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mListView.getLayoutParams();
params.height = mAdapter.getItemCount() * getResources().getDimensionPixelSize(R.dimen.row_height);
mListView.setLayoutParams(params);

Is still a workaround, but for basic cases it works.

What does status=canceled for a resource mean in Chrome Developer Tools?

A cancelled request happened to me when redirecting between secure and non-secure pages on separate domains within an iframe. The redirected request showed in dev tools as a "cancelled" request.

I have a page with an iframe containing a form hosted by my payment gateway. When the form in the iframe was submitted, the payment gateway would redirect back to a URL on my server. The redirect recently stopped working and ended up as a "cancelled" request instead.

It seems that Chrome (I was using Windows 7 Chrome 30.0.1599.101) no longer allowed a redirect within the iframe to go to a non-secure page on a separate domain. To fix it, I just made sure any redirected requests in the iframe were always sent to secure URLs.

When I created a simpler test page with only an iframe, there was a warning in the console (which I had previous missed or maybe didn't show up):

[Blocked] The page at https://mydomain.com/Payment/EnterDetails ran insecure content from http://mydomain.com/Payment/Success

The redirect turned into a cancelled request in Chrome on PC, Mac and Android. I don't know if it is specific to my website setup (SagePay Low Profile) or if something has changed in Chrome.

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

HTML iframe - disable scroll

Set all the content to:

#yourContent{
 width:100%;
height:100%;  // in you csss
}

The thing is that the iframe scroll is set by the content NOT by the iframe by itself.

set the content to 100% in the interior with CSS and the desired for the iframe in HTML

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Swift presentViewController

For me, I had two views in two separate nav controllers. I had to use a combination of the above.

var vc = self.storyboard?.instantiateViewControllerWithIdentifier("WelcomeViewController") as! WelcomeViewController
    var navigationController = UINavigationController(rootViewController: vc)
    self.presentViewController(navigationController, animated: true, completion: nil)

Swift 3.x

        let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "VC-ID" as! yourViewController
        let navigationVC = UINavigationController(rootViewController: secondVC)
        self.present(navigationVC, animated: true, completion: nil)

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

How to call javascript function on page load in asp.net

use your code within

  <script type="text/javascript">
     function window.onload()
       {

        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
       document.getElementById('<%= offSet.ClientID%>').value = retVal;

      }
  </script>

iOS 8 UITableView separator inset 0 not working

iOS introduces the layoutMargins property on cells AND table views.

This property isn't available in iOS 7.0 so you need to make sure you check before assigning it!

However, Apple has added a property called preservesSuperviewLayoutMargins to your cell that will prevent it from inheriting your Table View's margin settings. This way, your cells can configure their own margins independently of the table view. Think of it as an override.

This property is called preservesSuperviewLayoutMargins, and setting it to NO can allow you to override your Table View's layoutMargin settings with your own cell's layoutMargin setting. It both saves time (you don't have to modify the Table View's settings), and is more concise. Please refer to Mike Abdullah's answer for a detailed explanation.

NOTE: this is the proper, less messy implementation, as expressed in Mike Abdullah's answer; setting your cell's preservesSuperviewLayoutMargins=NO will ensure that your Table View does not override the cell settings.

First step - Setup your cell margins:

/*
    Tells the delegate that the table view is about to draw a cell for a particular row.
*/
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath)
{
    // Remove separator inset
    if cell.respondsToSelector("setSeparatorInset:") {
        cell.separatorInset = UIEdgeInsetsZero
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
        cell.preservesSuperviewLayoutMargins = false
    }

    // Explictly set your cell's layout margins
    if cell.respondsToSelector("setLayoutMargins:") {
        cell.layoutMargins = UIEdgeInsetsZero
    }
}

Setting the preservesSuperviewLayoutMargins property on your cell to NO should prevent your table view from overriding your cell margins. In some cases, it seems not to function properly.

Second step - Only if all fails, you may brute-force your Table View margins:

/*
    Called to notify the view controller that its view has just laid out its subviews.
*/
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Force your tableview margins (this may be a bad idea)
    if self.tableView.respondsToSelector("setSeparatorInset:") {
        self.tableView.separatorInset = UIEdgeInsetsZero
    }

    if self.tableView.respondsToSelector("setLayoutMargins:") {
        self.tableView.layoutMargins = UIEdgeInsetsZero
    }
}

...and there you go! This should work on iOS 8 as well as iOS 7.

Note: tested using iOS 8.1 and 7.1, in my case I only needed to use the first step of this explanation.

The Second Step is only required if you have unpopulated cell beneath the rendered cells, ie. if the table is larger than the number of rows in the table model. Not doing the second step would result in different separator offsets.

How can I rotate an HTML <div> 90 degrees?

you can use css3 property writing-mode writing-mode: tb-rl

css-tricks

mozilla

Set Matplotlib colorbar size to match graph

@bogatron already gave the answer suggested by the matplotlib docs, which produces the right height, but it introduces a different problem. Now the width of the colorbar (as well as the space between colorbar and plot) changes with the width of the plot. In other words, the aspect ratio of the colorbar is not fixed anymore.

To get both the right height and a given aspect ratio, you have to dig a bit deeper into the mysterious axes_grid1 module.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
import numpy as np

aspect = 20
pad_fraction = 0.5

ax = plt.gca()
im = ax.imshow(np.arange(200).reshape((20, 10)))
divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
cax = divider.append_axes("right", size=width, pad=pad)
plt.colorbar(im, cax=cax)

Note that this specifies the width of the colorbar w.r.t. the height of the plot (in contrast to the width of the figure, as it was before).

The spacing between colorbar and plot can now be specified as a fraction of the width of the colorbar, which is IMHO a much more meaningful number than a fraction of the figure width.

image plot with colorbar

UPDATE:

I created an IPython notebook on the topic, where I packed the above code into an easily re-usable function:

import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1

def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
    """Add a vertical color bar to an image plot."""
    divider = axes_grid1.make_axes_locatable(im.axes)
    width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
    pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
    current_ax = plt.gca()
    cax = divider.append_axes("right", size=width, pad=pad)
    plt.sca(current_ax)
    return im.axes.figure.colorbar(im, cax=cax, **kwargs)

It can be used like this:

im = plt.imshow(np.arange(200).reshape((20, 10)))
add_colorbar(im)

AngularJs: How to check for changes in file input fields?

This is a refinement of some of the other ones around, the data will end up in an ng-model, which is normally what you want.

Markup (just make an attribute data-file so the directive can find it)

<input
    data-file
    id="id_image" name="image"
    ng-model="my_image_model" type="file">

JS

app.directive('file', function() {
    return {
        require:"ngModel",
        restrict: 'A',
        link: function($scope, el, attrs, ngModel){
            el.bind('change', function(event){
                var files = event.target.files;
                var file = files[0];

                ngModel.$setViewValue(file);
                $scope.$apply();
            });
        }
    };
});

Calling C++ class methods via a function pointer

Minimal runnable example

main.cpp

#include <cassert>

class C {
    public:
        int i;
        C(int i) : i(i) {}
        int m(int j) { return this->i + j; }
};

int main() {
    // Get a method pointer.
    int (C::*p)(int) = &C::m;

    // Create a test object.
    C c(1);
    C *cp = &c;

    // Operator .*
    assert((c.*p)(2) == 3);

    // Operator ->*
    assert((cp->*p)(2) == 3);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Tested in Ubuntu 18.04.

You cannot change the order of the parenthesis or omit them. The following do not work:

c.*p(2)
c.*(p)(2)

GCC 9.2 would fail with:

main.cpp: In function ‘int main()’:
main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
   19 |     assert(c.*p(2) == 3);
      |

C++11 standard

.* and ->* are a single operators introduced in C++ for this purpose, and not present in C.

C++11 N3337 standard draft:

  • 2.13 "Operators and punctuators" has a list of all operators, which contains .* and ->*.
  • 5.5 "Pointer-to-member operators" explains what they do

How to call a function from another controller in angularjs?

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:

$scope.$parent.parentmethod();

You can try it over here

I want to align the text in a <td> to the top

I was facing such a problem, look at the picture below

enter image description here

and here is its HTML

<tr class="li1">
    <td valign="top">1.</td>
    <td colspan="5" valign="top">
        <p>How to build e-book learning environment</p>
    </td>
</tr>

so I fix it by changing valign Attribute in both td tags to baseline

and it worked

here is the result enter image description here

hope this help you

How can I access each element of a pair in a pair list?

When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].

Are vectors passed to functions by value or by reference in C++

void foo(vector<int> test)

vector would be passed by value in this.

You have more ways to pass vectors depending on the context:-

1) Pass by reference:- This will let function foo change your contents of the vector. More efficient than pass by value as copying of vector is avoided.

2) Pass by const-reference:- This is efficient as well as reliable when you don't want function to change the contents of the vector.

How to write macro for Notepad++?

Macros in Notepad++ are just a bunch of encoded operations: you start recording, operate on the buffer, perhaps activating menus, stop recording then play the macro.
After investigation, I found out they are saved in the file shortcuts.xml in the Macros section. For example, I have there:

<Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
    <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
    <Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
    <Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
</Macro>

I haven't looked at the source, but from the look, I would say we have messages sent to Scintilla (the editing component, perhaps type 0 and 1), and to Notepad++ itself (probably activating menu items).
I don't think it will record actions in dialogs (like search/replace).

Looking at Scintilla.iface file, we can see that 2170 is the code of ReplaceSel (ie. insert string is nothing is selected), 2327 is Tab command, and Resource Hacker (just have it handy...) shows that 42024 is "Trim Trailing Space" menu item and 41006 is "Save".
I guess action type 0 is for Scintilla commands with numerical params, type 1 is for commands with string parameter, 2 is for Notepad++ commands.

Problem: Scintilla doesn't have a "Replace all" command: it is the task of the client to do the iteration, with or without confirmation, etc.
Another problem: it seems type 1 action is limited to 1 char (I edited manually, when exiting N++ it was truncated).
I tried some tricks, but I fear such task is beyond the macro capabilities.

Maybe that's where SciTE with its Lua scripting ability (or Programmer's Notepad which seems to be scriptable with Python) has an edge... :-)

[EDIT] Looks like I got the above macro from this thread or a similar place... :-) I guess the first lines are unnecessary (side effect or recording) but they were good examples of macro code anyway.

How do I change the root directory of an Apache server?

I was working with LAMP and to change the document root folder, I have edited the default file which is there in the /etc/apache2/sites-available folder.

If you want to do the same, just edit as follows:

DocumentRoot /home/username/new_root_folder
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/username/new_root_folder>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

After this, if you type "localhost" in the browser, it will load the /home/username/new_root_folder content.

PHPMailer: SMTP Error: Could not connect to SMTP host

Since this questions shows up high in google, I'd like to share here my solution for the case where PHP was just upgraded to version 5.6 (which has stricter SSL behavior).

The PHPMailer wiki has a section on this:

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#php-56-certificate-verification-failure

The suggested workaround is including the following piece of code:

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

This should work for PHPMailer 5.2.10 (and up).

Note: Obviously, and also as suggested in that wiki, this should be a temporary solution!

The correct fix for this is to replace the invalid, misconfigured or self-signed certificate with a good one.

Initialize array of strings

Its fine to just do char **strings;, char **strings = NULL, or char **strings = {NULL}

but to initialize it you'd have to use malloc:

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

int main(){
    // allocate space for 5 pointers to strings
    char **strings = (char**)malloc(5*sizeof(char*));
    int i = 0;
    //allocate space for each string
    // here allocate 50 bytes, which is more than enough for the strings
    for(i = 0; i < 5; i++){
        printf("%d\n", i);
        strings[i] = (char*)malloc(50*sizeof(char));
    }
    //assign them all something
    sprintf(strings[0], "bird goes tweet");
    sprintf(strings[1], "mouse goes squeak");
    sprintf(strings[2], "cow goes moo");
    sprintf(strings[3], "frog goes croak");
    sprintf(strings[4], "what does the fox say?");
    // Print it out
    for(i = 0; i < 5; i++){
        printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
    } 
    //Free each string
    for(i = 0; i < 5; i++){
        free(strings[i]);
    }
    //finally release the first string
    free(strings);
    return 0;
}

Asynchronous vs synchronous execution, what does it really mean?

I think a good way to think of it is a classic running Relay Race

Synchronous: Processes like members of the same team, they won't execute until they receive baton (end of the execution of previous process/runner) and yet they are all acting in sync with each other.

Asynchronous: Where processes like members of different teams on the same relay race track, they will run and stop, async with each other, but within same race (overall program execution).

Does it make sense?

How to debug apk signed for release?

I tried with the following and it's worked:

release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

What is the effect of extern "C" in C++?

Just wanted to add a bit of info, since I haven't seen it posted yet.

You'll very often see code in C headers like so:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.

Although, I have also seen C++ code such as:

extern "C" {
#include "legacy_C_header.h"
}

which I imagine accomplishes much the same thing.

Not sure which way is better, but I have seen both.

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

Linux: where are environment variables stored?

The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in

/proc/pid/environ

This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do

cat /proc/3940/environ | tr '\0' '\n'

Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.

Why do I have ORA-00904 even when the column is present?

This happened to me when I accidentally defined two entities with the same persistent database table. In one of the tables the column in question did exist, in the other not. When attempting to persist an object (of the type referring to the wrong underlying database table), this error occurred.

Different names of JSON property during serialization and deserialization

You can use this variant:

import lombok.Getter;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;

//...

@JsonProperty(value = "rr") // for deserialization
@Getter(onMethod_ = {@JsonGetter(value = "r")}) // for serialization
private String rrrr;

with Lombok getter

JSON.parse vs. eval()

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:

var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"

eval(x)         //won't work
JSON.parse(x)   //does work

See this example.

How to pass parameters to maven build using pom.xml?

If we have parameter like below in our POM XML

<version>${project.version}.${svn.version}</version>
  <packaging>war</packaging>

I run maven command line as follows :

mvn clean install package -Dproject.version=10 -Dsvn.version=1

MySQL search and replace some text in a field

And if you want to search and replace based on the value of another field you could do a CONCAT:

update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));

Just to have this one here so that others will find it at once.

MySQL FULL JOIN?

SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
        orders AS o
ON      o.orderNo = p.p_id
UNION ALL
SELECT  NULL, NULL, orderNo
FROM    orders
WHERE   orderNo NOT IN
        (
        SELECT  p_id
        FROM    persons
        )

Undefined reference to `sin`

You need to link with the math library, libm:

$ gcc -Wall foo.c -o foo -lm 

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

Check if string has space in between (or anywhere)

It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.

var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true

How to use CSS to surround a number with a circle?

You can use the border-radius for this:

<html>
  <head>
    <style type="text/css">

    .round
    {
        -moz-border-radius: 15px;
        border-radius: 15px;
        padding: 5px;
        border: 1px solid #000;
    }

  </style>
  </head>  
  <body>   
    <span class="round">30</span>
  </body>
</html>  

Play with the border radius and the padding values until you are satisfied with the result.

But this won't work in all browsers. I guess IE still does not support rounded corners.

Integer value in TextView

It might be cleaner for some people to work with an Integer object so you can just call toString() directly on the object:

Integer length = my_text_view.getText().getLength();
counter_text_view.setText( length.toString() );

Today's Date in Perl in MM/DD/YYYY format

use DateTime qw();
DateTime->now->strftime('%m/%d/%Y')   

expression returns 06/13/2012

jQuery/JavaScript to replace broken images

(window.jQuery || window.Zepto).fn.fallback = function (fallback) {
  return this.one('error', function () {
    var self = this;
    this.src = (fallback || 'http://lorempixel.com/$width/$height').replace(
      /\$(\w+)/g, function (m, t) { return self[t] || ''; }
    );
  });
};
    

You can pass a placeholder path and acces in it all properties from the failed image object via $*:

$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');

http://jsfiddle.net/ARTsinn/Cu4Zn/

Why is processing a sorted array faster than processing an unsorted array?

In the same line (I think this was not highlighted by any answer) it's good to mention that sometimes (specially in software where the performance matters—like in the Linux kernel) you can find some if statements like the following:

if (likely( everything_is_ok ))
{
    /* Do something */
}

or similarly:

if (unlikely(very_improbable_condition))
{
    /* Do something */    
}

Both likely() and unlikely() are in fact macros that are defined by using something like the GCC's __builtin_expect to help the compiler insert prediction code to favour the condition taking into account the information provided by the user. GCC supports other builtins that could change the behavior of the running program or emit low level instructions like clearing the cache, etc. See this documentation that goes through the available GCC's builtins.

Normally this kind of optimizations are mainly found in hard-real time applications or embedded systems where execution time matters and it's critical. For example, if you are checking for some error condition that only happens 1/10000000 times, then why not inform the compiler about this? This way, by default, the branch prediction would assume that the condition is false.

Cannot install signed apk to device manually, got error "App not installed"

The same thing happened to me, as long as I generated my apk from Build> Build APK. I could install and un-install the apk as many times as they were without any problem, but instead if I generated the Build> Generate Signed APK, when I passed the apk to the phone and try to install it, it only allowed me one occasion, the same one that came out the following message:

enter image description here

until then everything was fine if I selected "INSTALL IN ANY WAY", but what happened if I uninstalled the app and wanted to reinstall it (a possible scenario), the following happened:

enter image description here

so I solved the problem by disabling play protect, which I achieved (within Google Play)> Menu> Play Protect> Search for security threats (disable).

enter image description here

enter image description here

CORS Access-Control-Allow-Headers wildcard being ignored?

Quoted from monsur,

The Access-Control-Allow-Headers header does not allow wildcards. It must be an exact match: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header.

So here is my php solution.

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  $headers=getallheaders();
  @$ACRH=$headers["Access-Control-Request-Headers"];
  header("Access-Control-Allow-Headers: $ACRH");
}

Regex to match string containing two names in any order

Explanation of command that i am going to write:-

. means any character, digit can come in place of .

* means zero or more occurrences of thing written just previous to it.

| means 'or'.

So,

james.*jack

would search james , then any number of character until jack comes.

Since you want either jack.*james or james.*jack

Hence Command:

jack.*james|james.*jack

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

CURL and HTTPS, "Cannot resolve host"

We need to add host security certificate to php.ini file. For local developement enviroment we can add cacert.pem in your local php.ini.

do phpinfo(); and file your php.ini path open and add uncomment ;curl.capath

curl.capath=path_of_your_cacert.pem

React prevent event bubbling in nested components on click

I had issues getting event.stopPropagation() working. If you do too, try moving it to the top of your click handler function, that was what I needed to do to stop the event from bubbling. Example function:

  toggleFilter(e) {
    e.stopPropagation(); // If moved to the end of the function, will not work
    let target = e.target;
    let i = 10; // Sanity breaker

    while(true) {
      if (--i === 0) { return; }
      if (target.classList.contains("filter")) {
        target.classList.toggle("active");
        break;
      }
      target = target.parentNode;
    }
  }

"405 method not allowed" in IIS7.5 for "PUT" method

Another important module that needs reconfiguring before PUT and DELETE will work is the options verb

<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="WebDAV" />
<add name="OPTIONSVerbHandler" path="*" verb="*" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="Script" />
</handlers>

Also see this post: https://stackoverflow.com/a/22018750/9376681

How to ensure a <select> form field is submitted when it is disabled?

Same solution suggested by Tres without using jQuery

<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">

   <select id="mysel" disabled="disabled">....</select>

   <input name="submit" id="submit" type="submit" value="SEND FORM">
</form>

This might help someone understand more, but obviously is less flexible than the jQuery one.

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.

There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.

Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.

How do I get a list of all subdomains of a domain?

  1. dig somedomain.com soa
  2. dig @ns.SOA.com somedomain.com axfr

Dropdown using javascript onchange

Something like this should do the trick

<select id="leave" onchange="leaveChange()">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

<div id="message"></div>

Javascript

function leaveChange() {
    if (document.getElementById("leave").value != "100"){
        document.getElementById("message").innerHTML = "Common message";
    }     
    else{
        document.getElementById("message").innerHTML = "Having a Baby!!";
    }        
}

jsFiddle Demo

A shorter version and more general could be

HTML

<select id="leave" onchange="leaveChange(this)">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

Javascript

function leaveChange(control) {
    var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
    document.getElementById("message").innerHTML = msg;
}

Unresolved external symbol in object files

sometimes if a new header file is added, and this error starts coming due to that, you need to add library as well to get rid of unresolved external symbol.

for example:

#include WtsApi32.h

will need:

#pragma comment(lib, "Wtsapi32.lib") 

How to add a second css class with a conditional value in razor MVC 4

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

Getting the names of all files in a directory with PHP

Little something I created for this:

function getFiles($path) {
    if (is_dir($path)) {
        $files = scandir($path);
        $res = [];
        foreach ($files as $key => $file) {
            if ($file != "." && $file != "..") {
                array_push($res, $file);
            }
        }
        return $res;
    }
    return false;
}

How to set .net Framework 4.5 version in IIS 7 application pool

Go to "Run" and execute this:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

NOTE: run as administrator.

Using the HTML5 "required" attribute for a group of checkboxes?

I had the same problem and I my solution was this:

HTML:

<form id="processForm.php" action="post">
  <div class="input check_boxes required wish_payment_type">
    <div class="wish_payment_type">
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_1">
        <input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
      </label>
    </span>
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_2">
        <input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
      </label>
    </span>
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_3">
        <input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz
      </label>

      <input id='submit' type="submit" value="Submit">
  </div>
</form>

JS:

var verifyPaymentType = function () {
  var checkboxes = $('.wish_payment_type .checkbox');
  var inputs = checkboxes.find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
}

$('#submit').click(verifyPaymentType);

https://jsfiddle.net/oywLo5z4/

Laravel - Forbidden You don't have permission to access / on this server

For me, It was just because I had a folder in my public_html named as same as that route!
so please check if you don't have a folder with the address of that route!
hope be helpful

How to format a string as a telephone number in C#

 Label12.Text = Convert.ToInt64(reader[6]).ToString("(###) ###-#### ");

This is my example! I hope can help you with this. regards

How to convert milliseconds to seconds with precision

Why don't you simply try

System.out.println(1500/1000.0);
System.out.println(500/1000.0);

Permission denied error on Github Push

Based on the information that the original poster has provided so far, it might be the case that the project owners of EasySoftwareLicensing/software-licensing-php will only accept pull requests from forks, so you may need to fork the main repo and push to your fork, then make pull requests from it to the main repo.

See the following GitHub help articles for instructions:

  1. Fork a Repo.
  2. Collaborating.

Node / Express: EADDRINUSE, Address already in use - Kill server

FYI, you can kill the process in one command sudo fuser -k 3000/tcp. This can be done for all other ports like 8000, 8080 or 9000 which are commonly used for development.

how to get login option for phpmyadmin in xampp

If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").

How to locate the php.ini file (xampp)

This is one of those "you were technically accurate, but you didn't answer my question" but it doesn't mean the above were wrong or misguided - they just didn't run into my issue.

So, I figure I'll give an answer.

As the others mentioned (spot on), I created a file:

<?php
phpinfo(); 
?>

So that worked great. However, it showed "(none)"

So where do you find (none)!?

In my case, on Windows, you just go to where php is installed; I had already had installed it in c:\php I believe it would be the same steps on other platforms.

Then, from a command line, powershell for ex, type: notepad c:\php\php.ini

Tell it yes, you do want to create it, then add whatever changes you needed in the first place. For me, for example:

extension_dir = "c:\php\ext"
extension=mysqli
upload_max_filesize = 25M
post_max_size = 13M
max_execution_time = 300

Then save. Fixed!

By the way - if you do "file new" and then "save as" Notepad will helpfully rename your file to php.ini.txt. Friends let friends NOT AVOID THE CLI.

How to populate a sub-document in mongoose after creating it?

In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: 'User' }).

Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate as usual (e.g. populate('comments.created_by'))

Proof of concept code:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

Finally note that populate works only for queries so you need to first pass your item into a query and then call it:

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

How do I remove a comma off the end of a string?

A simple regular expression would work

$string = preg_replace("/,$/", "", $string)

How to convert list of key-value tuples into dictionary?

This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required

THAT is your actual question.

The answer is that the elements of your list are not what you think they are. If you type myList[0] you will find that the first element of your list is not a two-tuple, e.g. ('A', 1), but rather a 1916-length iterable.

Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]), all you need to do is dict(myList).

What is the correct way of reading from a TCP socket in C/C++?

Without knowing your full application it is hard to say what the best way to approach the problem is, but a common technique is to use a header which starts with a fixed length field, which denotes the length of the rest of your message.

Assume that your header consist only of a 4 byte integer which denotes the length of the rest of your message. Then simply do the following.

// This assumes buffer is at least x bytes long,
// and that the socket is blocking.
void ReadXBytes(int socket, unsigned int x, void* buffer)
{
    int bytesRead = 0;
    int result;
    while (bytesRead < x)
    {
        result = read(socket, buffer + bytesRead, x - bytesRead);
        if (result < 1 )
        {
            // Throw your error.
        }

        bytesRead += result;
    }
}

Then later in the code

unsigned int length = 0;
char* buffer = 0;
// we assume that sizeof(length) will return 4 here.
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);

// Then process the data as needed.

delete [] buffer;

This makes a few assumptions:

  • ints are the same size on the sender and receiver.
  • Endianess is the same on both the sender and receiver.
  • You have control of the protocol on both sides
  • When you send a message you can calculate the length up front.

Since it is common to want to explicitly know the size of the integer you are sending across the network define them in a header file and use them explicitly such as:

// These typedefs will vary across different platforms
// such as linux, win32, OS/X etc, but the idea
// is that a Int8 is always 8 bits, and a UInt32 is always
// 32 bits regardless of the platform you are on.
// These vary from compiler to compiler, so you have to 
// look them up in the compiler documentation.
typedef char Int8;
typedef short int Int16;
typedef int Int32;

typedef unsigned char UInt8;
typedef unsigned short int UInt16;
typedef unsigned int UInt32;

This would change the above to:

UInt32 length = 0;
char* buffer = 0;

ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);

// process

delete [] buffer;

I hope this helps.

substring index range

Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end.

To make life easier for substring operation, imagine that characters are between indexes.

0 1 2 3 4 5 6 7 8 9 10  <- available indexes for substring 
 u n i v E R S i t y
        ?     ?
      start  end --> range of "E R S"

Quoting the docs:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

How to search in array of object in mongodb

You can do this in two ways:

  1. ElementMatch - $elemMatch (as explained in above answers)

    db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })

  2. Use $and with find

    db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})

What is the difference between a string and a byte string?

Assuming Python 3 (in Python 2, this difference is a little less well-defined) - a string is a sequence of characters, ie unicode codepoints; these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of, unsurprisingly, bytes - things that can be stored on disk. The mapping between them is an encoding - there are quite a lot of these (and infinitely many are possible) - and you need to know which applies in the particular case in order to do the conversion, since a different encoding may map the same bytes to a different string:

>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-16')
'?????'
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-8')
'to??o?'

Once you know which one to use, you can use the .decode() method of the byte string to get the right character string from it as above. For completeness, the .encode() method of a character string goes the opposite way:

>>> 'to??o?'.encode('utf-8')
b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'

Get only part of an Array in Java?

If you are using Java 1.6 or greater, you can use Arrays.copyOfRange to copy a portion of the array. From the javadoc:

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

Here is a simple example:

/**
 * @Program that Copies the specified range of the specified array into a new 
 * array.
 * CopyofRange8Array.java 
 * Author:-RoseIndia Team
 * Date:-15-May-2008
 */
import java.util.*;
public class CopyofRange8Array {
    public static void main(String[] args) {
       //creating a short array
       Object T[]={"Rose","India","Net","Limited","Rohini"};
        // //Copies the specified  short array upto specified range,
        Object T1[] = Arrays.copyOfRange(T, 1,5);
        for (int i = 0; i < T1.length; i++) 
            //Displaying the Copied short array upto specified range
            System.out.println(T1[i]);
    }

}

mcrypt is deprecated, what is the alternative?

As pointed out, you should not be storing your users' passwords in a format that is decryptable. Reversable encryption provides an easy route for hackers to find out your users' passwords, which extends to putting your users' accounts at other sites at risk should they use the same password there.

PHP provides a pair of powerful functions for random-salted, one-way hash encryption — password_hash() and password_verify(). Because the hash is automatically random-salted, there is no way for hackers to utilize precompiled tables of password hashes to reverse-engineer the password. Set the PASSWORD_DEFAULT option and future versions of PHP will automatically use stronger algorithms to generate password hashes without you having to update your code.

Configuration with name 'default' not found. Android Studio

For one, it doesn't do good to have more than one settings.gradle file -- it only looks at the top-level one.

When you get this "Configuration with name 'default' not found" error, it's really confusing, but what it means is that Gradle is looking for a module (or a build.gradle) file someplace, and it's not finding it. In your case, you have this in your settings.gradle file:

include ':libraries:Android-Bootstrap',':Android-Bootstrap'

which is making Gradle look for a library at FTPBackup/libraries/Android-Bootstrap. If you're on a case-sensitive filesystem (and you haven't mistyped Libraries in your question when you meant libraries), it may not find FTPBackup/Libraries/Android-Bootstrap because of the case difference. It's also looking for another library at FTPBackup/Android-Bootstrap, and it's definitely not going to find one because that directory isn't there.

This should work:

include ':Libraries:Android-Bootstrap'

You need the same case-sensitive spec in your dependencies block:

compile project (':Libraries:Android-Bootstrap')

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

How might I schedule a C# Windows Service to perform a task daily?

The way I accomplish this is with a timer.

Run a server timer, have it check the Hour/Minute every 60 seconds.

If it's the right Hour/Minute, then run your process.

I actually have this abstracted out into a base class I call OnceADayRunner.

Let me clean up the code a bit and I'll post it here.

    private void OnceADayRunnerTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (NDC.Push(GetType().Name))
        {
            try
            {
                log.DebugFormat("Checking if it's time to process at: {0}", e.SignalTime);
                log.DebugFormat("IsTestMode: {0}", IsTestMode);

                if ((e.SignalTime.Minute == MinuteToCheck && e.SignalTime.Hour == HourToCheck) || IsTestMode)
                {
                    log.InfoFormat("Processing at: Hour = {0} - Minute = {1}", e.SignalTime.Hour, e.SignalTime.Minute);
                    OnceADayTimer.Enabled = false;
                    OnceADayMethod();
                    OnceADayTimer.Enabled = true;

                    IsTestMode = false;
                }
                else
                {
                    log.DebugFormat("Not correct time at: Hour = {0} - Minute = {1}", e.SignalTime.Hour, e.SignalTime.Minute);
                }
            }
            catch (Exception ex)
            {
                OnceADayTimer.Enabled = true;
                log.Error(ex.ToString());
            }

            OnceADayTimer.Start();
        }
    }

The beef of the method is in the e.SignalTime.Minute/Hour check.

There are hooks in there for testing, etc. but this is what your elapsed timer could look like to make it all work.

Android Shared preferences for creating one time activity (example)

Write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
 editor.commit(); 

Read from Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

%Like% Query in spring JpaRepository

I use this:

@Query("Select c from Registration c where lower(c.place) like lower(concat('%', concat(:place, '%')))")

lower() is like toLowerCase in String, so the result isn't case sensitive.

CSS Selector for <input type="?"

You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...

Swift performSelector:withObject:afterDelay: is unavailable

You could do this:

var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

SWIFT 3

let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

There can be only one auto column

Note also that "key" does not necessarily mean primary key. Something like this will work:

CREATE TABLE book (
    isbn             BIGINT NOT NULL PRIMARY KEY,
    id               INT    NOT NULL AUTO_INCREMENT,
    accepted_terms   BIT(1) NOT NULL,
    accepted_privacy BIT(1) NOT NULL,
    INDEX(id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

This is a contrived example and probably not the best idea, but it can be very useful in certain cases.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I have been dealing with this problem for a while. I have changed everything as described in this post and even thought error occured. In that case make sure that you clean the project when changing settings in .xml or .properties file. In eclipse environment. Choose Project -> Clean

Difference between FetchType LAZY and EAGER in Java Persistence API?

Basically,

LAZY = fetch when needed
EAGER = fetch immediately

Copying sets Java

With Java 8 you can use stream and collect to copy the items:

Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());

Or you can collect to an ImmutableSet (if you know that the set should not change):

Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());

Grant Select on a view not base table when base table is in a different database

I also had this problem. I used information from link, mentioned above, and found quick solution. If you have different schema, lets say test, and create user utest, owner of schema test and among views in schema test you have view vTestView, based on tables from schema dbo, while selecting from it you'll get error mentioned above - no access to base objects. It was enough for me to execute statement

ALTER AUTHORIZATION ON test.vTestView TO dbo;

which means that I change an ownership of vTextView from schema it belongs to (test) to database user dbo, owner of schema dbo. After that without any other permissions required user utest will be able to access data from test.vTestView

Opposite of %in%: exclude rows with values specified in a vector

purrr::compose() is another quick way to define this for later use, as in:

`%!in%` <- compose(`!`, `%in%`)

Connection to SQL Server Works Sometimes

It turned out that TCP/IP was enabled for the IPv4 address, but not for the IPv6 address, of THESERVER.

Apparently some connection attempts ended up using IPv4 and others used IPv6.

Enabling TCP/IP for both IP versions resolved the issue.

The fact that SSMS worked turned out to be coincidental (the first few attempts presumably used IPv4). Some later attempts to connect through SSMS resulted in the same error message.

To enable TCP/IP for additional IP addresses:

  • Start Sql Server Configuration Manager
  • Open the node SQL Server Network Configuration
  • Left-click Protocols for MYSQLINSTANCE
  • In the right-hand pane, right-click TCP/IP
  • Click Properties
  • Select the IP Addresses tab
  • For each listed IP address, ensure Active and Enabled are both Yes.

How to send a correct authorization header for basic authentication

PHP - curl:

$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...

PHP - POST in WordPress:

$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode("$username:$password")
  )
));
...

How to fix "The ConnectionString property has not been initialized"

You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).

If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.

var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);

If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.

Post your code (for the databound element and the web.config to be safe) and we can take a look at it.

EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString (if ConnectionString is the name of your connection string.)

How to open html file?

I encountered this problem today as well. I am using Windows and the system language by default is Chinese. Hence, someone may encounter this Unicode error similarly. Simply add encoding = 'utf-8':

with open("test.html", "r", encoding='utf-8') as f:
    text= f.read()

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

Vue.js—Difference between v-model and v-bind

v-model
it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.

v-model is used only for HTML input elements

ex: <input type="text" v-model="name" > 

v-bind
it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element. v-bind is used to bind html attribute
ex:
<input type="text" v-bind:class="abc" v-bind:value="">

<a v-bind:href="home/abc" > click me </a>

How to increase buffer size in Oracle SQL Developer to view all records?

https://forums.oracle.com/forums/thread.jspa?threadID=447344

The pertinent section reads:

There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.

There is also a button on the toolbar which is a "Fetch All" button.

FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.

As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows() procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.

How to set Internet options for Android emulator?

You can do it using AVD Manager, choose Tools -> Options. Set HTTP Proxy Server to 8.8.8.8,8.8.4.4

The emulator will be connected.

int to unsigned int conversion

with a little help of math

#include <math.h>
int main(){
  int a = -1;
  unsigned int b;
  b = abs(a);
}

How to use java.Set

The first thing you need to study is the java.util.Set API.

Here's a small example of how to use its methods:

    Set<Integer> numbers = new TreeSet<Integer>();

    numbers.add(2);
    numbers.add(5);

    System.out.println(numbers); // "[2, 5]"
    System.out.println(numbers.contains(7)); // "false"

    System.out.println(numbers.add(5)); // "false"
    System.out.println(numbers.size()); // "2"

    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    System.out.println("Sum = " + sum); // "Sum = 7"

    numbers.addAll(Arrays.asList(1,2,3,4,5));
    System.out.println(numbers); // "[1, 2, 3, 4, 5]"

    numbers.removeAll(Arrays.asList(4,5,6,7));
    System.out.println(numbers); // "[1, 2, 3]"

    numbers.retainAll(Arrays.asList(2,3,4,5));
    System.out.println(numbers); // "[2, 3]"

Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

In a nutshell:

  • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
    • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
  • For non-null references x, y, z, equals must be:
    • reflexive: x.equals(x).
    • symmetric: x.equals(y) if and only if y.equals(x)
    • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
    • consistent: x.equals(y) must not change unless the objects have mutated
    • x.equals(null) == false
  • The general contract for hashCode is:
    • consistent: return the same number unless mutation happened
    • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
      • strictly speaking, object inequality does not require hash code inequality
      • but hash code inequality necessarily requires object inequality
  • What counts as mutation should be consistent between equals and hashCode.

Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


Further readings on stackoverflow:

How to show google.com in an iframe?

You can bypass X-Frame-Options in an using YQL.

var iframe = document.getElementsByTagName('iframe')[0];
var url = iframe.src;
var getData = function (data) {
    if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
    else if (data && data.error && data.error.description) loadHTML(data.error.description);
    else loadHTML('Error: Cannot load ' + url);
};
var loadURL = function (src) {
    url = src;
    var script = document.createElement('script');
    script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
    document.body.appendChild(script);
};
var loadHTML = function (html) {
    iframe.src = 'about:blank';
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
    iframe.contentWindow.document.close();
}

loadURL(iframe.src);
<iframe src="http://www.google.co.in" width="500" height="300"></iframe>

Run it here: http://jsfiddle.net/2gou4yen/

Code from here: How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

How do I put an already-running process under nohup?

  1. ctrl + z - this will pause the job (not going to cancel!)
  2. bg - this will put the job in background and return in running process
  3. disown -a - this will cut all the attachment with job (so you can close the terminal and it will still run)

These simple steps will allow you to close the terminal while keeping process running.

It wont put on nohup (based on my understanding of your question, you don't need it here).

Find the index of a dict within a list, by matching the dict's value

lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]

tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
# 1

If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

def build_dict(seq, key):
    return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.

#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1

It's ok to have comment and blank lines before them.

How to install package from github repo in Yarn

You can add any Git repository (or tarball) as a dependency to yarn by specifying the remote URL (either HTTPS or SSH):

yarn add <git remote url> installs a package from a remote git repository.
yarn add <git remote url>#<branch/commit/tag> installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball.

Here are some examples:

yarn add https://github.com/fancyapps/fancybox [remote url]
yarn add ssh://github.com/fancyapps/fancybox#3.0  [branch]
yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit]

(Note: Fancybox v2.6.1 isn't available in the Git version.)

To support both npm and yarn, you can use the git+url syntax:

git+https://github.com/owner/package.git#commithashortagorbranch
git+ssh://github.com/owner/package.git#commithashortagorbranch

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

This error happened to me in a Grails Application with the JTDS Driver 1.3.0 (SQL Server). The problem was an incorrect login in SQL Server. After solve this issue (in SQL Server) my app was correctly deployed in Tomcat. Tip: I saw the error in stacktrace.log

Get safe area inset top and bottom heights

UIWindow *window = [[[UIApplication sharedApplication] delegate] window]; 
CGFloat fBottomPadding = window.safeAreaInsets.bottom;

Possible to perform cross-database queries with PostgreSQL?

Just to add a bit more information.

There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.

contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.

PostgreSQL FAQ

Is there a way to specify which pytest tests to run from a file?

Method 1: Randomly selected tests. Long and ugly.

python -m pytest test/stress/test_performance.py::TestPerformance::test_continuous_trigger test/integration/test_config.py::TestConfig::test_valid_config

Method 2: Use Keyword Expressions.

Note: I am searching by testcase names. Same is applicable to TestClass names.

Case 1: The below will run whichever is found. Since we have used 'OR' .

python -m pytest -k 'test_password_valid or test_no_configuration'

Lets say the two above are actually correct, 2 tests will be run.

Case 2: Now an incorrect name and another correct name.

python -m pytest -k 'test_password_validzzzzzz or test_no_configuration' 

Only one is found and run.

Case 3: If you want all tests to run or no one, then use AND

python -m pytest -k 'test_password_valid and test_no_configuration'

Both will be run if correct or none.

Case 4: Run test only in one folder:

python -m pytest test/project1/integration -k 'test_password_valid or test_no_configuration'

Case 5: Run test from only one file.

python -m pytest test/integration/test_authentication.py -k 'test_password_expiry or test_incorrect_password'

Case 6: Run all tests except the match.

python -m pytest test/integration/test_authentication.py -k 'not  test_incorrect_password'

get selected value in datePicker and format it

$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});

var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');

$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');

var result = $('#scheduleDate').val();

alert('result: ' + result);

result: 20, April, 2012

pass post data with window.location.href

Use this file : "jquery.redirect.js"

$("#btn_id").click(function(){
    $.redirect(http://localhost/test/test1.php,
        {
            user_name: "khan",
            city : "Meerut",
            country : "country"
        });
    });
});

see https://github.com/mgalante/jquery.redirect

Write HTML string in JSON

4 Things You Must Do When Putting HTML in JSON:

1) Escape quotation marks used around HTML attributes like so <img src=\"someimage.png\" />

2) Escape the forward slash in HTML end tags. <div>Hello World!<\/div>. This is an ancient artifact of an old HTML spec that didn't want HTML parsers to get confused when putting strings in a <SCRIPT> tag. For some reason, today’s browsers still like it.

3) This one was totally bizarre. You should include a space between the tag name and the slash on self-closing tags. I have no idea why this is, but on MOST modern browsers, if you try using javascript to append a <li> tag as a child of an unordered list that is formatted like so: <ul/>, it won't work. It gets added to the DOM after the ul tag. But, if the code looks like this: <ul /> (notice the space before the /), everything works fine. Very strange indeed.

4) Be sure to encode any quotation marks that might be included in (bad) HTML content. This is the only thing that would really break the JSON by accidentally terminating the string early. Any " characters should be encoded as &quot; if it is meant to be included as HTML content.

via

How do I check if there are duplicates in a flat list?

Recommended for short lists only:

any(thelist.count(x) > 1 for x in thelist)

Do not use on a long list -- it can take time proportional to the square of the number of items in the list!

For longer lists with hashable items (strings, numbers, &c):

def anydup(thelist):
  seen = set()
  for x in thelist:
    if x in seen: return True
    seen.add(x)
  return False

If your items are not hashable (sublists, dicts, etc) it gets hairier, though it may still be possible to get O(N logN) if they're at least comparable. But you need to know or test the characteristics of the items (hashable or not, comparable or not) to get the best performance you can -- O(N) for hashables, O(N log N) for non-hashable comparables, otherwise it's down to O(N squared) and there's nothing one can do about it:-(.

Best way to handle list.index(might-not-exist) in python?

It's been quite some time but it's a core part of the stdlib and has dozens of potential methods so I think it's useful to have some benchmarks for the different suggestions and include the numpy method which can be by far the fastest.

import random
from timeit import timeit
import numpy as np

l = [random.random() for i in range(10**4)]
l[10**4 - 100] = 5

# method 1
def fun1(l:list, x:int, e = -1) -> int:
    return [[i for i,elem in enumerate(l) if elem == x] or [e]][0]

# method 2
def fun2(l:list, x:int, e = -1) -> int:
    for i,elem in enumerate(l):
        if elem == x:
            return i
    else:
        return e

# method 3
def fun3(l:list, x:int, e = -1) -> int:
    try:
        idx = l.index(x)
    except ValueError:
        idx = e
    return idx

# method 4
def fun4(l:list, x:int, e = -1) -> int:
    return l.index(x) if x in l else e

l2 = np.array(l)
# method 5
def fun5(l:list or np.ndarray, x:int, e = -1) -> int:
    res = np.where(np.equal(l, x))
    if res[0].any():
        return res[0][0]
    else:        
        return e


if __name__ == "__main__":
    print("Method 1:")
    print(timeit(stmt = "fun1(l, 5)", number = 1000, globals = globals()))
    print("")
    print("Method 2:")
    print(timeit(stmt = "fun2(l, 5)", number = 1000, globals = globals()))
    print("")
    print("Method 3:")
    print(timeit(stmt = "fun3(l, 5)", number = 1000, globals = globals()))
    print("")
    print("Method 4:")
    print(timeit(stmt = "fun4(l, 5)", number = 1000, globals = globals()))
    print("")
    print("Method 5, numpy given list:")
    print(timeit(stmt = "fun5(l, 5)", number = 1000, globals = globals()))
    print("")
    print("Method 6, numpy given np.ndarray:")
    print(timeit(stmt = "fun5(l2, 5)", number = 1000, globals = globals()))
    print("")

When run as main, this results in the following printout on my machine indicating time in seconds to complete 1000 trials of each function:

Method 1: 0.7502102799990098

Method 2: 0.7291318440002215

Method 3: 0.24142152300009911

Method 4: 0.5253471979995084

Method 5, numpy given list: 0.5045417560013448

Method 6, numpy given np.ndarray: 0.011147511999297421

Of course the question asks specifically about lists so the best solution is to use the try-except method, however the speed improvements (at least 20x here compared to try-except) offered by using the numpy data structures and operators instead of python data structures is significant and if building something on many arrays of data that is performance critical then the author should try to use numpy throughout to take advantage of the superfast C bindings. (CPython interpreter, other interpreter performances may vary)

Btw, the reason Method 5 is much slower than Method 6 is because numpy first has to convert the given list to it's own numpy array, so giving it a list doesn't break it it just doesn't fully utilise the speed possible.

highlight the navigation menu for the current page

It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm, You could try something like this might still be some configuration

a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}


div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}

Android, landscape only orientation?

Just two steps needed:

  1. Apply setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); after setContentView().

  2. In the AndroidMainfest.xml, put this statement <activity android:name=".YOURCLASSNAME" android:screenOrientation="landscape" />

Hope it helps and happy coding :)

How to center an iframe horizontally?

The simplest code to align the iframe element:

<div align="center"><iframe width="560" height="315" src="www.youtube.com" frameborder="1px"></iframe></div>

Is there an easy way to reload css without reloading the page?

Based on previous solutions, I have created bookmark with JavaScript code:

javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);

Image from Firefox:

enter image description here

What does it do?

It reloads CSS by adding query string params (as solutions above):

How to remove all non-alpha numeric characters from a string in MySQL?

if you are using php then....

try{
$con = new PDO ("mysql:host=localhost;dbname=dbasename","root","");
}
catch(PDOException $e){
echo "error".$e-getMessage();   
}

$select = $con->prepare("SELECT * FROM table");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();

while($data=$select->fetch()){ 

$id = $data['id'];
$column = $data['column'];
$column = preg_replace("/[^a-zA-Z0-9]+/", " ", $column); //remove all special characters

$update = $con->prepare("UPDATE table SET column=:column WHERE id='$id'");
$update->bindParam(':column', $column );
$update->execute();

// echo $column."<br>";
} 

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

I know this is an old post but I was looking up something similar... I think your issue was that when you use Now(), the output will be "6/20/2014"... This an issue for a file name as it has "/" in it. As you may know, you cannot use certain symbols in a file name.

Cheers

How to calculate modulus of large numbers?

Okay, so you want to calculate a^b mod m. First we'll take a naive approach and then see how we can refine it.

First, reduce a mod m. That means, find a number a1 so that 0 <= a1 < m and a = a1 mod m. Then repeatedly in a loop multiply by a1 and reduce again mod m. Thus, in pseudocode:

a1 = a reduced mod m
p = 1
for(int i = 1; i <= b; i++) {
    p *= a1
    p = p reduced mod m
}

By doing this, we avoid numbers larger than m^2. This is the key. The reason we avoid numbers larger than m^2 is because at every step 0 <= p < m and 0 <= a1 < m.

As an example, let's compute 5^55 mod 221. First, 5 is already reduced mod 221.

  1. 1 * 5 = 5 mod 221
  2. 5 * 5 = 25 mod 221
  3. 25 * 5 = 125 mod 221
  4. 125 * 5 = 183 mod 221
  5. 183 * 5 = 31 mod 221
  6. 31 * 5 = 155 mod 221
  7. 155 * 5 = 112 mod 221
  8. 112 * 5 = 118 mod 221
  9. 118 * 5 = 148 mod 221
  10. 148 * 5 = 77 mod 221
  11. 77 * 5 = 164 mod 221
  12. 164 * 5 = 157 mod 221
  13. 157 * 5 = 122 mod 221
  14. 122 * 5 = 168 mod 221
  15. 168 * 5 = 177 mod 221
  16. 177 * 5 = 1 mod 221
  17. 1 * 5 = 5 mod 221
  18. 5 * 5 = 25 mod 221
  19. 25 * 5 = 125 mod 221
  20. 125 * 5 = 183 mod 221
  21. 183 * 5 = 31 mod 221
  22. 31 * 5 = 155 mod 221
  23. 155 * 5 = 112 mod 221
  24. 112 * 5 = 118 mod 221
  25. 118 * 5 = 148 mod 221
  26. 148 * 5 = 77 mod 221
  27. 77 * 5 = 164 mod 221
  28. 164 * 5 = 157 mod 221
  29. 157 * 5 = 122 mod 221
  30. 122 * 5 = 168 mod 221
  31. 168 * 5 = 177 mod 221
  32. 177 * 5 = 1 mod 221
  33. 1 * 5 = 5 mod 221
  34. 5 * 5 = 25 mod 221
  35. 25 * 5 = 125 mod 221
  36. 125 * 5 = 183 mod 221
  37. 183 * 5 = 31 mod 221
  38. 31 * 5 = 155 mod 221
  39. 155 * 5 = 112 mod 221
  40. 112 * 5 = 118 mod 221
  41. 118 * 5 = 148 mod 221
  42. 148 * 5 = 77 mod 221
  43. 77 * 5 = 164 mod 221
  44. 164 * 5 = 157 mod 221
  45. 157 * 5 = 122 mod 221
  46. 122 * 5 = 168 mod 221
  47. 168 * 5 = 177 mod 221
  48. 177 * 5 = 1 mod 221
  49. 1 * 5 = 5 mod 221
  50. 5 * 5 = 25 mod 221
  51. 25 * 5 = 125 mod 221
  52. 125 * 5 = 183 mod 221
  53. 183 * 5 = 31 mod 221
  54. 31 * 5 = 155 mod 221
  55. 155 * 5 = 112 mod 221

Therefore, 5^55 = 112 mod 221.

Now, we can improve this by using exponentiation by squaring; this is the famous trick wherein we reduce exponentiation to requiring only log b multiplications instead of b. Note that with the algorithm that I described above, the exponentiation by squaring improvement, you end up with the right-to-left binary method.

a1 = a reduced mod m
p = 1
while (b > 0) {
     if (b is odd) {
         p *= a1
         p = p reduced mod m
     }
     b /= 2
     a1 = (a1 * a1) reduced mod m
}

Thus, since 55 = 110111 in binary

  1. 1 * (5^1 mod 221) = 5 mod 221
  2. 5 * (5^2 mod 221) = 125 mod 221
  3. 125 * (5^4 mod 221) = 112 mod 221
  4. 112 * (5^16 mod 221) = 112 mod 221
  5. 112 * (5^32 mod 221) = 112 mod 221

Therefore the answer is 5^55 = 112 mod 221. The reason this works is because

55 = 1 + 2 + 4 + 16 + 32

so that

5^55 = 5^(1 + 2 + 4 + 16 + 32) mod 221
     = 5^1 * 5^2 * 5^4 * 5^16 * 5^32 mod 221
     = 5 * 25 * 183 * 1 * 1 mod 221
     = 22875 mod 221
     = 112 mod 221

In the step where we calculate 5^1 mod 221, 5^2 mod 221, etc. we note that 5^(2^k) = 5^(2^(k-1)) * 5^(2^(k-1)) because 2^k = 2^(k-1) + 2^(k-1) so that we can first compute 5^1 and reduce mod 221, then square this and reduce mod 221 to obtain 5^2 mod 221, etc.

The above algorithm formalizes this idea.

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

Checking character length in ruby

Verification, do not forget the to_s

 def nottolonng?(value)
   if value.to_s.length <=8
     return true
   else
     return false
   end
  end

How good is Java's UUID.randomUUID?

Wikipedia has a very good answer http://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions

the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:

...

This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes.

...

Thus, for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated.

How to perform an SQLite query within an Android application?

I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.

SQLiteDatabase db = helper.getReadableDatabase();

String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";

Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

Parameters

  • table: the name of the table you want to query
  • columns: the column names that you want returned. Don't return data that you don't need.
  • selection: the row data that you want returned from the columns (This is the WHERE clause.)
  • selectionArgs: This is substituted for the ? in the selection String above.
  • groupBy and having: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.
  • orderBy: sort the data
  • limit: limit the number of results to return

How to send POST in angularjs with multiple params?

It depends on what is your backend technology. If your backend technology accepting JSON data. data:{id:1,name:'name',...}

otherwise, you need to convert your data best way to do that creating Factory to convert your data to id=1&name=name&...

then on $http define content-type. you can find full article @https://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).success(function () {});

ref:How do I POST urlencoded form data with $http in AngularJS?

!important about encodeURIComponent(obj[p]) will transfer object the way implicit. like a date value will be converted to a string like=>'Fri Feb 03 2017 09:56:57 GMT-0700 (US Mountain Standard Time)' which I don't have any clue how you can parse it at least in back-end C# code. (I mean code that doesn't need more than 2-line) you can use (angular.isDate, value.toJSON) in date case to convert it to more meaningful format for your back-end code.

I'm using this function to comunicating to my backend webservices...

 this.SendUpdateRequest = (url, data) => {
            return $http({
                method: 'POST',
                url: url,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (obj) { return jsontoqs(obj); },
                data: { jsonstring: JSON.stringify(data) }
            });
        }; 

and bellow code to use it...

webrequest.SendUpdateRequest(
  '/Services/ServeicNameWebService.asmx/Update',
  $scope.updatedto)
  .then(
      (res) => { /*/TODO/*/ },
      (err) => { /*/TODO/*/ }
);

in backend C# I'm using newtonsoft for deserializing the data.

Python: can't assign to literal

1 is a literal. name = value is an assignment. 1 = value is an assignment to a literal, which makes no sense. Why would you want 1 to mean something other than 1?

CSS last-child selector: select last-element of specific class, not last child inside of parent?

What about this solution?

div.commentList > article.comment:not(:last-child):last-of-type
{
    color:red; /*or whatever...*/
}

Why is using onClick() in HTML a bad practice?

  • onclick events run in the global scope and may cause unexpected error.
  • Adding onclick events to many DOM elements will slow down the
    performance and efficiency.

How to convert characters to HTML entities using plain JavaScript

Demo on JSFiddle

here's a tiny stand alone method that:

  • attempts to consolidate the answers on this page, without using a library
  • works in older browsers
  • supports surrogate pairs (like emojis)
  • applies character overrides (what's that? not sure exactly)

i don't know too much about unicode, but it seems to be working well.

// escape a string for display in html
// see also: 
// polyfill for String.prototype.codePointAt
//   https://raw.githubusercontent.com/mathiasbynens/String.prototype.codePointAt/master/codepointat.js
// how to convert characters to html entities
//     http://stackoverflow.com/a/1354491/347508
// html overrides from 
//   https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides / http://stackoverflow.com/questions/1354064/how-to-convert-characters-to-html-entities-using-plain-javascript/23831239#comment36668052_1354098

var _escape_overrides = { 0x00:'\uFFFD',0x80:'\u20AC',0x82:'\u201A',0x83:'\u0192',0x84:'\u201E',0x85:'\u2026',0x86:'\u2020',0x87:'\u2021',0x88:'\u02C6',0x89:'\u2030',0x8A:'\u0160',0x8B:'\u2039',0x8C:'\u0152',0x8E:'\u017D',0x91:'\u2018',0x92:'\u2019',0x93:'\u201C',0x94:'\u201D',0x95:'\u2022',0x96:'\u2013',0x97:'\u2014',0x98:'\u02DC',0x99:'\u2122',0x9A:'\u0161',0x9B:'\u203A',0x9C:'\u0153',0x9E:'\u017E',0x9F:'\u0178' }; 

function escapeHtml(str){
    return str.replace(/([\u0000-\uD799]|[\uD800-\uDBFF][\uDC00-\uFFFF])/g, function(c) {
        var c1 = c.charCodeAt(0);
        // ascii character, use override or escape
        if( c1 <= 0xFF ) return (c1=_escape_overrides[c1])?c1:escape(c).replace(/%(..)/g,"&#x$1;");
        // utf8/16 character
        else if( c.length == 1 ) return "&#" + c1 + ";"; 
        // surrogate pair
        else if( c.length == 2 && c1 >= 0xD800 && c1 <= 0xDBFF ) return "&#" + ((c1-0xD800)*0x400 + c.charCodeAt(1) - 0xDC00 + 0x10000) + ";"
        // no clue .. 
        else return "";
    });
}

IOError: [Errno 32] Broken pipe: Python

To bring Alex L.'s helpful answer, akhan's helpful answer, and Blckknght's helpful answer together with some additional information:

  • Standard Unix signal SIGPIPE is sent to a process writing to a pipe when there's no process reading from the pipe (anymore).

    • This is not necessarily an error condition; some Unix utilities such as head by design stop reading prematurely from a pipe, once they've received enough data.
  • By default - i.e., if the writing process does not explicitly trap SIGPIPE - the writing process is simply terminated, and its exit code is set to 141, which is calculated as 128 (to signal termination by signal in general) + 13 (SIGPIPE's specific signal number).

  • By design, however, Python itself traps SIGPIPE and translates it into a Python IOError instance with errno value errno.EPIPE, so that a Python script can catch it, if it so chooses - see Alex L.'s answer for how to do that.

  • If a Python script does not catch it, Python outputs error message IOError: [Errno 32] Broken pipe and terminates the script with exit code 1 - this is the symptom the OP saw.

  • In many cases this is more disruptive than helpful, so reverting to the default behavior is desirable:

    • Using the signal module allows just that, as stated in akhan's answer; signal.signal() takes a signal to handle as the 1st argument and a handler as the 2nd; special handler value SIG_DFL represents the system's default behavior:

      from signal import signal, SIGPIPE, SIG_DFL
      signal(SIGPIPE, SIG_DFL) 
      

Where can I find documentation on formatting a date in JavaScript?

Formatting and especially parsing dates in JavaScript can be a bit of a headache. Not all browsers handle dates in the same way. So while it's useful to know the base methods, its more practical to use a helper library.

The XDate javascript library by Adam Shaw has been around since mid-2011 and is still under active development. It has fantastic documentation, a great API, formatting, tries to remain backwards-compatible and even supports localized strings.

Link to changing the locale strings: https://gist.github.com/1221376

Getting list of files in documents folder

Simple and dynamic solution (Swift 5):

extension FileManager {

  class func directoryUrl() -> URL? {
      let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
      return paths.first
  }

  class func allRecordedData() -> [URL]? {
     if let documentsUrl = FileManager.directoryUrl() {
        do {
            let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
            return directoryContents.filter{ $0.pathExtension == "m4a" }
        } catch {
            return nil
        }
     }
     return nil
  }}

Hide text using css

Try this code to shorten and hide text

_x000D_
_x000D_
.hidetxt{_x000D_
_x000D_
  width: 346px;_x000D_
  display: table-caption;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  cursor: no-drop;_x000D_
  _x000D_
}_x000D_
_x000D_
.hidetxt:hover { _x000D_
_x000D_
  visibility: hidden;_x000D_
  _x000D_
}
_x000D_
<div class="hidetxt">_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or to hide use in your css class .hidetxt { visibility: hidden; }

How to create a template function within a class? (C++)

See here: Templates, template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void    Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

Can I apply a CSS style to an element name?

You can use attribute selectors but they won't work in IE6 like meder said, there are javascript workarounds to that tho. Check Selectivizr

More detailed into on attribute selectors: http://www.css3.info/preview/attribute-selectors/

/* turns all input fields that have a name that starts with "go" red */
input[name^="go"] { color: red }

jquery <a> tag click event

All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.

Scale image to fit a bounding box

Here's a hackish solution I discovered:

#image {
    max-width: 10%;
    max-height: 10%;
    transform: scale(10);
}

This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container.

Unlike the background-image solution, this will also work with <video> elements.

Interactive example:

_x000D_
_x000D_
 function step(timestamp) {
     var container = document.getElementById('container');
     timestamp /= 1000;
     container.style.left   = (200 + 100 * Math.sin(timestamp * 1.0)) + 'px';
     container.style.top    = (200 + 100 * Math.sin(timestamp * 1.1)) + 'px';
     container.style.width  = (500 + 500 * Math.sin(timestamp * 1.2)) + 'px';
     container.style.height = (500 + 500 * Math.sin(timestamp * 1.3)) + 'px';
     window.requestAnimationFrame(step);
 }

 window.requestAnimationFrame(step);
_x000D_
 #container {
     outline: 1px solid black;
     position: relative;
     background-color: red;
 }
 #image {
     display: block;
     max-width: 10%;
     max-height: 10%;
     transform-origin: 0 0;
     transform: scale(10);
 }
_x000D_
<div id="container">
    <img id="image" src="https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png">
</div>
_x000D_
_x000D_
_x000D_

get one item from an array of name,value JSON

To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:

Array.prototype.get = function(name) {
    for (var i=0, len=this.length; i<len; i++) {
        if (typeof this[i] != "object") continue;
        if (this[i].name === name) return this[i].value;
    }
};

this will add the get() method to all arrays and let you do what you want, i.e:

arr.get('k1'); //= abc

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

Understanding PIVOT function in T-SQL

To set Compatibility error

use this before using pivot function

ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100  

how to prevent css inherit

lets say you have this:

<ul>
    <li></li>
    <li>
        <ul>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li></li>
<ul>

Now if you DONT need IE6 compatibility (reference at Quirksmode) you can have the following css

ul li { background:#fff; }
ul>li { background:#f0f; }

The > is a direct children operator, so in this case only the first level of lis will be purple.

Hope this helps

Find running median from a stream of integers

If you can't hold all the items in memory at once, this problem becomes much harder. The heap solution requires you to hold all the elements in memory at once. This is not possible in most real world applications of this problem.

Instead, as you see numbers, keep track of the count of the number of times you see each integer. Assuming 4 byte integers, that's 2^32 buckets, or at most 2^33 integers (key and count for each int), which is 2^35 bytes or 32GB. It will likely be much less than this because you don't need to store the key or count for those entries that are 0 (ie. like a defaultdict in python). This takes constant time to insert each new integer.

Then at any point, to find the median, just use the counts to determine which integer is the middle element. This takes constant time (albeit a large constant, but constant nonetheless).

How to use Chrome's network debugger with redirects

This has been changed since v32, thanks to @Daniel Alexiuc & @Thanatos for their comments.


Current (= v32)

At the top of the "Network" tab of DevTools, there's a checkbox to switch on the "Preserve log" functionality. If it is checked, the network log is preserved on page load.

Chrome v33 DevTools Network Tab: Preserve Log

The little red dot on the left now has the purpose to switch network logging on and off completely.


Older versions

In older versions of Chrome (v21 here), there's a little, clickable red dot in the footer of the "Network" tab.

Chrome v22 DevTools Network Tab: Preserve Log Upon Navigation

If you hover over it, it will tell you, that it will "Preserve Log Upon Navigation" when it is activated. It holds the promise.

Getting value from table cell in JavaScript...not jQuery

confer below code


<html>
<script>


    function addRow(){
 var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e =table.rows.length-1;
var l =table.rows[e].cells.length;
//x.innerHTML = "&nbsp;";
 for (var c =0,  m=l; c < m; c++) {
table.rows[0].insertCell(c);
   table.rows[0].cells[c].innerHTML  = "&nbsp;&nbsp;";
}

}




function addColumn(){
       var table = document.getElementById('myTable');
        for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].insertCell(0);
                table.rows[r].cells[0].innerHTML =  "&nbsp;&nbsp;" ;

        }

    }

function deleteRow() {
    document.getElementById("myTable").deleteRow(0);

}

function deleteColumn() {
   // var row = document.getElementById("myRow");
 var table = document.getElementById('myTable');
 for (var r = 0, n = table.rows.length; r < n; r++) {
    table.rows[r].deleteCell(0);//var table handle 
}
}

</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0       style='cursor:hand'>
    <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
    <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
    <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

    <table  id='myTable' border=1 cellpadding=0 cellspacing=0>
 <tr id='myRow'>          
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
<tr>          
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>

    </table>



</body>
</html>

mysql update query with sub query

You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as; eav_attributes

Then you can use those to set whichever role to any other role for all products like so;

UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`

The above will set all your 'base' roles to the 'small' image of the same product.

Where to place the 'assets' folder in Android Studio?

In Android Studio 4.1.1

Right Click on your module (app for example) -> New -> Folder -> Assets Folder

enter image description here

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.