Programs & Examples On #Executescalar

Cannot implicitly convert type 'int?' to 'int'.

If you're concerned with the possible null return value, you can also run something like this:

int ordersPerHour;  // can't be int? as it's different from method signature
// ... do stuff ... //
ordersPerHour = (dbcommand.ExecuteScalar() as int?).GetValueOrDefault();

This way you'll deal with the potential unexpected results and can also provide a default value to the expression, by entering .GetValueOrDefault(-1) or something more meaningful to you.

How can I use a C++ library from node.js?

There newer ways to connect Node.js and C++. Please, loot at Nan.

EDIT The fastest and easiest way is nbind. If you want to write asynchronous add-on you can combine Asyncworker class from nan.

Way to run Excel macros from command line or batch file?

The method shown below allows to run defined Excel macro from batch file, it uses environment variable to pass macro name from batch to Excel.

Put this code to the batch file (use your paths to EXCEL.EXE and to the workbook):

Set MacroName=MyMacro
"C:\Program Files\Microsoft Office\Office15\EXCEL.EXE" "C:\MyWorkbook.xlsm"

Put this code to Excel VBA ThisWorkBook Object:

Private Sub Workbook_Open()
    Dim strMacroName As String
    strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
    If strMacroName <> "" Then Run strMacroName
End Sub

And put your code to Excel VBA Module, like as follows:

Sub MyMacro()
    MsgBox "MyMacro is running..."
End Sub

Launch the batch file and get the result:

macro's dialog

For the case when you don't intend to run any macro just put empty value Set MacroName= to the batch.

Selenium -- How to wait until page is completely loaded

yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again

understand it with a dummy code

// clicking on view details 
driver.findElement(By.id("")).click();
// closing the pop up 
driver.findElement(By.id("")).click();


// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost 
// so to overcome this you have to re identify the locator strategy for add item 
// Please note : this is one of the way to overcome stale element exception 

// Step 1 please add a universal wait in your script like below 
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

Class vs. static method in JavaScript

There are tree ways methods and properties are implemented on function or class objects, and on they instances.

  1. On the class (or function) itself : Foo.method() or Foo.prop. Those are static methods or properties
  2. On its prototype : Foo.prototype.method() or Foo.prototype.prop. When created, the instances will inherit those object via the prototype witch is {method:function(){...}, prop:...}. So the foo object will receive, as prototype, a copy of the Foo.prototype object.
  3. On the instance itself : the method or property is added to the object itself. foo={method:function(){...}, prop:...}

The this keyword will represent and act differently according to the context. In a static method, it will represent the class itself (witch is after all an instance of Function : class Foo {} is quite equivalent to let Foo = new Function({})

With ECMAScript 2015, that seems well implemented today, it is clearer to see the difference between class (static) methods and properties, instance methods and properties and own methods ans properties. You can thus create three method or properties having the same name, but being different because they apply to different objects, the this keyword, in methods, will apply to, respectively, the class object itself and the instance object, by the prototype or by its own.

class Foo {
  constructor(){super();}
  
  static prop = "I am static" // see 1.
  static method(str) {alert("static method"+str+" :"+this.prop)} // see 1.
  
  prop="I am of an instance"; // see 2.
  method(str) {alert("instance method"+str+" : "+this.prop)} // see 2.
}

var foo= new Foo();
foo.prop = "I am of own";  // see 3.
foo.func = function(str){alert("own method" + str + this.prop)} // see 3.

Saving excel worksheet to CSV files with filename+worksheet name using VB

I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.

Here's my code behind a command button


Private Sub cmdSave()
    Dim sFileName As String
    Dim WB As Workbook

    Application.DisplayAlerts = False

    sFileName = "MyFileName.csv"
    'Copy the contents of required sheet ready to paste into the new CSV
    Sheets(1).Range("A1:T85").Copy 'Define your own range

    'Open a new XLS workbook, save it as the file name
    Set WB = Workbooks.Add
    With WB
        .Title = "MyTitle"
        .Subject = "MySubject"
        .Sheets(1).Select
        ActiveSheet.Paste
        .SaveAs "MyDirectory\" & sFileName, xlCSV
        .Close
    End With

    Application.DisplayAlerts = True
End Sub

This works for me :-)

How to send email from Terminal?

Go into Terminal and type man mail for help.

You will need to set SMTP up:

http://hints.macworld.com/article.php?story=20081217161612647

See also:

http://www.mactricksandtips.com/2008/09/send-mail-over-your-network.html

Eg:

mail -s "hello" "[email protected]" <<EOF
hello
world
EOF

This will send an email to [email protected] with the subject hello and the message

Hello

World

How to restart a node.js server

In this case you are restarting your node.js server often because it's in active development and you are making changes all the time. There is a great hot reload script that will handle this for you by watching all your .js files and restarting your node.js server if any of those files have changed. Just the ticket for rapid development and test.

The script and explanation on how to use it are at here at Draco Blue.

How to format Joda-Time DateTime to only mm/dd/yyyy?

Another way of doing that is:

String date = dateAndTime.substring(0, dateAndTime.indexOf(" "));

I'm not exactly certain, but I think this might be faster/use less memory than using the .split() method.

remote rejected master -> master (pre-receive hook declined)

I also faced the same issue The solution for this is

Delete the package-lock.json file on both the client and server

Make sure that you are using at least the LTS version of Node locally

Make sure your local Node version matches what is shown in the package.json file's engines property.

Run the git add . , git commit -m "fixing versions" and git push heroku master commands to force a rebuild.

HashMap with multiple values under the same key

Just for the record, the pure JDK8 solution would be to use Map::compute method:

map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);

Such as

public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();

    put(map, "first", "hello");
    put(map, "first", "foo");
    put(map, "bar", "foo");
    put(map, "first", "hello");

    map.forEach((s, strings) -> {
        System.out.print(s + ": ");
        System.out.println(strings.stream().collect(Collectors.joining(", ")));
    });
}

private static <KEY, VALUE> void put(Map<KEY, List<VALUE>> map, KEY key, VALUE value) {
    map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
}

with output:

bar: foo
first: hello, foo, hello

Note that to ensure consistency in case multiple threads access this data structure, ConcurrentHashMap and CopyOnWriteArrayList for instance need to be used.

How do I count the number of occurrences of a char in a String?

My 'idiomatic one-liner' for this is:

int count = StringUtils.countMatches("a.b.c.d", ".");

Why write it yourself when it's already in commons lang?

Spring Framework's oneliner for this is:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

how to make negative numbers into positive

abs() is for integers only. For floating point, use fabs() (or one of the fabs() line with the correct precision for whatever a actually is)

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Using HTML and Local Images Within UIWebView

Use this:

[webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];

How to get the number of threads in a Java process

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

How do I get the difference between two Dates in JavaScript?

If you use Date objects and then use the getTime() function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers.

If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp

SQL order string as number

This will handle negative numbers, fractions, string, everything:

ORDER BY ISNUMERIC(col) DESC, Try_Parse(col AS decimal(10,2)), col;

Compare two objects with .equals() and == operator

The overwrite function equals() is wrong. The object "a" is an instance of the String class and "object2" is an instance of the MyClass class. They are different classes, so the answer is "false".

Angular 2 'component' is not a known element

These are the 5 steps I perform when I got such an error.

  • Are you sure the name is correct? (also check the selector defined in the component)
  • Declare the component in a module?
  • If it is in another module, export the component?
  • If it is in another module, import that module?
  • Restart the cli?

When the error eccors during unit testing, make sure your declared the component or imported the module in TestBed.configureTestingModule

I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

You can't declare a component twice. You should declare and export your component in a new separate module. Next you should import this new module in every module you want to use your component.

It is hard to tell when you should create new module and when you shouldn't. I usually create a new module for every component I reuse. When I have some components that I use almost everywhere I put them in a single module. When I have a component that I don't reuse I won't create a separate module until I need it somewhere else.

Though it might be tempting to put all you components in a single module, this is bad for the performance. While developing, a module has to recompile every time changes are made. The bigger the module (more components) the more time it takes. Making a small change to big module takes more time than making a small change in a small module.

How does one add keyboard languages and switch between them in Linux Mint 16?

This assumes you have other languages already added in Language Support. (To check this, Menu > Language Support)

Now to make the keyboard language appear in the Panel:

  • Menu > Keyboard > Layouts > Add (+)

The icon 'en' or your language should now appear in the right panel tray. Click it to switch language.

In previous Mint versions, the shortcut for switching language was LEFT SHIFT + CAPS.

It seems now there is no default, and it must be added:

  • System settings > Keyboard > Layouts > Options > Switching to another layout

Keyboard Preferences is also accessible by right-clicking the language icon in the Panel.

How do I use .woff fonts for my website?

You need to declare @font-face like this in your stylesheet

@font-face {
  font-family: 'Awesome-Font';
  font-style: normal;
  font-weight: 400;
  src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}

Now if you want to apply this font to a paragraph simply use it like this..

p {
font-family: 'Awesome-Font', Arial;
}

More Reference

Checking character length in ruby

I think you could just use the String#length method...

http://ruby-doc.org/core-1.9.3/String.html#method-i-length

Example:

text = 'The quick brown fox jumps over the lazy dog.'
puts text.length > 25 ? 'Too many characters' : 'Accepted'

Correlation heatmap

The code below will produce this plot:

enter image description here

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]

# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]

# A dataframe
df = pd.DataFrame(data)

def CorrMtx(df, dropDuplicates = True):

    # Your dataset is already a correlation matrix.
    # If you have a dateset where you need to include the calculation
    # of a correlation matrix, just uncomment the line below:
    # df = df.corr()

    # Exclude duplicate correlations by masking uper right values
    if dropDuplicates:    
        mask = np.zeros_like(df, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

    # Set background color / chart style
    sns.set_style(style = 'white')

    # Set up  matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))

    # Add diverging colormap from red to blue
    cmap = sns.diverging_palette(250, 10, as_cmap=True)

    # Draw correlation plot with or without duplicates
    if dropDuplicates:
        sns.heatmap(df, mask=mask, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
    else:
        sns.heatmap(df, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)


CorrMtx(df, dropDuplicates = False)

I put this together after it was announced that the outstanding seaborn corrplot was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of 0.95173379, try changing to -0.95173379 and you'll get this:

enter image description here

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

img tag displays wrong orientation

If you have access to Linux, then open a terminal, cd to the directory containing your images and then run

mogrify -auto-orient *

This should permanently fix the orientation issues on all the images.

Sizing elements to percentage of screen width/height

This might be a little more clear:

double width = MediaQuery.of(context).size.width;

double yourWidth = width * 0.65;

Hope this solved your problem.

Linux: command to open URL in default browser

At least on Debian and all its derivatives, there is a 'sensible-browser' shell script which choose the browser best suited for the given url.

http://man.he.net/man1/sensible-browser

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

How to change default text color using custom theme?

Check if your activity layout overrides the theme, look for your activity layout located at layout/*your_activity*.xml and look for TextView that contains android:textColor="(some hex code") something like that on activity layout, and remove it. Then run your code again.

Why isn't my Pandas 'apply' function referencing multiple columns working?

This is same as the previous solution but I have defined the function in df.apply itself:

df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1)

Attach the Java Source Code

Just remove the JRE in Preferences>Java>Installed JRE and add the folder of your JDK. If you just add JDK but still leave JRE it won't work

Select query to get data from SQL Server

you can use ExecuteScalar() in place of ExecuteNonQuery() to get a single result use it like this

Int32 result= (Int32) command.ExecuteScalar();
Console.WriteLine(String.Format("{0}", result));

It will execute the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

As you want only one row in return, remove this use of SqlDataReader from your code

using (SqlDataReader reader = command.ExecuteReader())
{
    // iterate your results here
    Console.WriteLine(String.Format("{0}",reader["id"]));
}

because it will again execute your command and effect your page performance.

Sql Server trigger insert values from new row into another table

In a SQL Server trigger you have available two psdeuotables called inserted and deleted. These contain the old and new values of the record.

So within the trigger (you can look up the create trigger parts easily) you would do something like this:

Insert table2 (user_id, user_name)
select user_id, user_name from inserted i
left join table2 t on i.user_id = t.userid
where t.user_id is null

When writing triggers remember they act once on the whole batch of information, they do not process row-by-row. So account for multiple row inserts in your code.

Learning Ruby on Rails

I actually have an article about getting started with rails that should help. The only part of your question it doesn't cover is the OS. Mac is the dominant player here, believe it or not! But I use Ubuntu happily. There are gedit plugins that get you very close to TextMate - in fact, I like gedit better.

If you're on a windows machine and can use linux, that's definitely a better way to go. Rails on Windows has a lot of issues.

Format JavaScript date as yyyy-mm-dd

If the date needs to be the same across all time zones, for example represents some value from the database, then be sure to use UTC versions of the day, month, fullyear functions on the JavaScript date object as this will display in UTC time and avoid off-by-one errors in certain time zones.

Even better, use the Moment.js date library for this sort of formatting.

How to set commands output as a variable in a batch file

Some notes and some tricks.

The 'official' way to assign result to a variable is with FOR /F though in the other answers is shown how a temporary file can be used also.

For command processing FOR command has two forms depending if the usebackq option is used. In the all examples below the whole output is used without splitting it.

FOR /f "tokens=* delims=" %%A in ('whoami') do @set "I-Am=%%A"
FOR /f "usebackq tokens=* delims=" %%A in (`whoami`) do @set "I-Am=%%A"

and if used directly in the console:

FOR /f "tokens=* delims=" %A in ('whoami') do set "I-Am=%A"
FOR /f "usebackq tokens=* delims=" %A in (`whoami`) do set "I-Am=%A"

%%A is a temporary variable available only on the FOR command context and is called token.The two forms can be useful in case when you are dealing with arguments containing specific quotes. It is especially useful with REPL interfaces of other languages or WMIC. Though in both cases the expression can be put in double quotes and it still be processed.

Here's an example with python (it is possible to transition the expression in the brackets on a separate line which is used for easier reading):

@echo off

for /f "tokens=* delims=" %%a in (
  '"python -c ""print("""Message from python""")"""'
) do (
    echo processed message from python: "%%a"
)

To use an assigned variable in the same FOR block check also the DELAYED EXPANSION

And some tricks

To save yourself from writing all the arguments for the FOR command you can use MACRO for assigning the result to variable:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

the first argument to the macro is the command and the second the name of the variable we want to use and both are separated by , (comma). Though this is suitable only for straight forward scenarios.

If we want a similar macro for the console we can use DOSKEY

doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"
rem  -- example --
assign WHOAMI /LOGONID,my-id
echo %my-id%

DOSKEY does accept double quotes as enclosion for arguments so this also is useful for more simple scenarios.

FOR also works well with pipes which can be used for chaining commands (though it is not so good for assigning a variable.

hostname |for /f "tokens=* delims=" %%# in ('more') do @(ping %%#)

Which also can be beautified with macros:

@echo off
:: --- defining chain command macros ---
set "result-as-[arg]:=|for /f "tokens=* delims=" %%# in ('more') do @("
set "[arg]= %%#)"
:::  --------------------------  :::

::Example:
hostname %result-as-[arg]:% ping %[arg]%

And for completnes macros for the temp file approach (no doskey definition ,but it also can be easy done.If you have a SSD this wont be so slow):

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

For /f with another macro:

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Finding the length of a Character Array in C

You can use this function:

int arraySize(char array[])
{
    int cont = 0;
    for (int i = 0; array[i] != 0; i++)
            cont++;
    return cont;
}

How to uninstall Jenkins?

These instructions apply if you installed using the official Jenkins Mac installer from http://jenkins-ci.org/

Execute uninstall script from terminal:

'/Library/Application Support/Jenkins/Uninstall.command'

or use Finder to navigate into that folder and double-click on Uninstall.command.

Finally delete last configuration bits which might have been forgotten:

sudo rm -rf /var/root/.jenkins ~/.jenkins

If the uninstallation script cannot be found (older Jenkins version), use following commands:

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins "/Library/Application Support/Jenkins" /Library/Documentation/Jenkins

and if you want to get rid of all the jobs and builds:

sudo rm -rf /Users/Shared/Jenkins

and to delete the jenkins user and group (if you chose to use them):

sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins

These commands are also invoked by the uninstall script in newer Jenkins versions, and should be executed too:

sudo rm -f /etc/newsyslog.d/jenkins.conf
pkgutil --pkgs | grep 'org\.jenkins-ci\.' | xargs -n 1 sudo pkgutil --forget

ORA-28040: No matching authentication protocol exception

I was using eclipse and after trying all the other answers it didn't work for me. In the end, what worked for me was moving the ojdb7.jar to top in the Build Path. This occurs when multiple jars have conflicting same classes.

  1. Select project in Project Explorer
  2. Right click on Project -> Build Path -> Configure Build Path
  3. Go to Order and Export tab and select ojdbc.jar
  4. Click button TOP to move it to top

how to use javascript Object.defineProperty

Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...

Self Join to get employee manager name

   SELECT b.Emp_id, b.Emp_name,e.emp_id as managerID, e.emp_name as managerName
    FROM Employee b
    JOIN Employee e ON b.Emp_ID = e.emp_mgr_id

Try this, it's a JOIN on itself to get the manager :)

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of text like in a messenger

 >>> stex[40]
 array(['Know the famous thing ...

and you want to get statistics from the corpus (text col=11) you first must get the values from dataframe (df5) and then join all records together in one single corpus:

 >>> stex = (df5.ix[0:,[11]]).values
 >>> a_str = ','.join(str(x) for x in stex)
 >>> a_str = a_str.split()
 >>> fd2 = nltk.FreqDist(a_str)
 >>> fd2.most_common(50)

How do I do a bulk insert in mySQL using node.js

Few things I want to mention is that I'm using mysql package for making a connection with my database and what you saw below is working code and written for insert bulk query.

const values = [
  [1, 'DEBUG', 'Something went wrong. I have to debug this.'],
  [2, 'INFO', 'This just information to end user.'],
  [3, 'WARNING', 'Warning are really helping users.'],
  [4, 'SUCCESS', 'If everything works then your request is successful']
];

const query = "INSERT INTO logs(id, type, desc) VALUES ?";

const query = connection.query(query, [values], function(err, result) {
  if (err) {
    console.log('err', err)
  }

  console.log('result', result)
});

What is Haskell used for in the real world?

This is a pretty good source for info about Haskell and its uses:

Open Source Haskell Releases and Growth

Giving a border to an HTML table row, <tr>

Make use of CSS classes:

tr.border{
    outline: thin solid;
}

and use it like:

<tr class="border">...</tr>

ASP.NET MVC Razor render without encoding

@(new HtmlString(myString))

How to insert strings containing slashes with sed?

add \ before special characters:

s/\?page=one&/page\/one\//g

etc.

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.

Update

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Insert multiple rows with one query MySQL

Here are a few ways to do it

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip' 
from SOMETABLEWITHTONSOFROWS LIMIT 3;

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

Append a single character to a string or char array in java?

And for those who are looking for when you have to concatenate a char to a String rather than a String to another String as given below.

char ch = 'a';
String otherstring = "helen";
// do this
otherstring = otherstring + "" + ch;
System.out.println(otherstring);
// output : helena

How to exclude file only from root folder in Git

If the above solution does not work for you, try this:

#1.1 Do NOT ignore file pattern in  any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php

##########################

# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php

How do I make a JSON object with multiple arrays?

var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]

Substring a string from the end of the string

You can do:

string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

Which Radio button in the group is checked?

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).

How to unpack and pack pkg file?

In addition to what @abarnert said, I today had to find out that the default cpio utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:

find ./Foo.app | cpio -o --format odc | gzip -c > Payload

$date + 1 year?

I prefer the OO approach:

$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))

Use DateTimeImmutable otherwise you will modify the original date too! more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php


If you just want from todays date then you can always do:

new \DateTimeImmutable('-1 Month');

Open link in new tab or window

You can simply do that by setting target="_blank", w3schools has an example.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

This is the answer in 2017. urllib3 not a part of requests anymore

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

Java replace all square brackets in a string

use regex [\\[\\]] -

String str = "[Chrissman-@1]";
String[] temp = str.replaceAll("[\\[\\]]", "").split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);

output -

Nickname: Chrissman | Power: 1

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

findViewByID returns null

Alongside the classic causes, mentioned elsewhere:

  • Make sure you've called setContentView() before findViewById()
  • Make sure that the id you want is in the view or layout you've given to setContentView()
  • Make sure that the id isn't accidentally duplicated in different layouts

There is one I have found for custom views in standard layouts, which goes against the documentation:

In theory you can create a custom view and add it to a layout (see here). However, I have found that in such situations, sometimes the id attribute works for all the views in the layout except the custom ones. The solution I use is:

  1. Replace each custom view with a FrameLayout with the same layout properties as you would like the custom view to have. Give it an appropriate id, say frame_for_custom_view.
  2. In onCreate:

    setContentView(R.layout.my_layout);
    FrameView fv = findViewById(R.id.frame_for_custom_layout);
    MyCustomView cv = new MyCustomView(context);
    fv.addView(cv);
    

    which puts the custom view in the frame.

Most efficient way to increment a Map value in Java

If you're using Eclipse Collections, you can use a HashBag. It will be the most efficient approach in terms of memory usage and it will also perform well in terms of execution speed.

HashBag is backed by a MutableObjectIntMap which stores primitive ints instead of Counter objects. This reduces memory overhead and improves execution speed.

HashBag provides the API you'd need since it's a Collection that also allows you to query for the number of occurrences of an item.

Here's an example from the Eclipse Collections Kata.

MutableBag<String> bag =
  HashBag.newBagWith("one", "two", "two", "three", "three", "three");

Assert.assertEquals(3, bag.occurrencesOf("three"));

bag.add("one");
Assert.assertEquals(2, bag.occurrencesOf("one"));

bag.addOccurrences("one", 4);
Assert.assertEquals(6, bag.occurrencesOf("one"));

Note: I am a committer for Eclipse Collections.

LINQ to SQL - Left Outer Join with multiple join conditions

It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.

Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):

SELECT f.value
  FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
      AND f.otherid = 17
UNION
SELECT NULL AS value
  FROM period as p
WHERE p.companyid = 100
      AND NOT EXISTS ( 
                      SELECT * 
                        FROM facts AS f
                       WHERE p.id = f.periodid
                             AND f.otherid = 17
                     );

So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).

However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.

How to efficiently remove duplicates from an array without using Set

  public static void main(String[] args) { 
            int input[] = { 1, 5, 1, 0, -3, 1, -3, 2, 1 }; 
            int j = 0; 
            int output[] = new int[100]; 
            Arrays.fill(a, 0); 
            for (int i = 0; i < 9; i++) { 
                    if (output[input[i]] == 0) {
                            input[j++] = input[i]; 
                            output[input[i]]++; 
                    } 
            } 
            for (int i = 0; i < j; i++) { 
                    System.out.print(input[i] + " "); 
            } 
    }

Vertical Align Center in Bootstrap 4

Because none of the above worked for me, I am adding another answer.

Goal: To vertically and horizontally align a div on a page using bootstrap 4 flexbox classes.

Step 1: Set your outermost div to a height of 100vh. This sets the height to 100% of the Veiwport Height. If you don't do this, nothing else will work. Setting it to a height of 100% is only relative to the parent, so if the parent is not the full height of the viewport, nothing will work. In the example below, I set the Body to 100vh.

Step 2: Set the container div to be the flexbox container with the d-flex class.

Step 3: Center div horizontally with the justify-content-center class.

Step 4: Center div vertically with the align-items-center

Step 5: Run page, view your vertically and horizontally centered div.

Note that there is no special class that needs to be set on the centered div itself (the child div)

<body style="background-color:#f2f2f2; height:100vh;">

<div class="h-100 d-flex justify-content-center align-items-center">
    <div style="height:600px; background-color:white; width:600px;">
</div>

</div>

</body>

How to activate "Share" button in android app?

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="files"
        path="."/>

    <external-path
        name="external_files"
        path="."/>
</paths>

now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>

now you put the below code in the setOnLongClickListener :

share_btn.setOnClickListener {
    try {
        val file = File("pathOfFile")
        if(file.exists()) {
            val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        toast("Error")
    }
}

nginx: send all requests to a single html page

I think this will do it for you:

location / {
    try_files /base.html =404;
}

javascript regular expression to check for IP addresses

Regular expression for the IP address format:

/^(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])$/;

What's the best way to trim std::string?

Bit late to the party, but never mind. Now C++11 is here, we have lambdas and auto variables. So my version, which also handles all-whitespace and empty strings, is:

#include <cctype>
#include <string>
#include <algorithm>

inline std::string trim(const std::string &s)
{
   auto wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});
   auto wsback=std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();
   return (wsback<=wsfront ? std::string() : std::string(wsfront,wsback));
}

We could make a reverse iterator from wsfront and use that as the termination condition in the second find_if_not but that's only useful in the case of an all-whitespace string, and gcc 4.8 at least isn't smart enough to infer the type of the reverse iterator (std::string::const_reverse_iterator) with auto. I don't know how expensive constructing a reverse iterator is, so YMMV here. With this alteration, the code looks like this:

inline std::string trim(const std::string &s)
{
   auto  wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});
   return std::string(wsfront,std::find_if_not(s.rbegin(),std::string::const_reverse_iterator(wsfront),[](int c){return std::isspace(c);}).base());
}

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

Serializing enums with Jackson

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and implement custom serializer:

public class OrderTypeSerializer extends JsonSerializer<OrderType> {

  @Override
  public void serialize(OrderType value, JsonGenerator generator,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

    generator.writeStartObject();
    generator.writeFieldName("id");
    generator.writeNumber(value.getId());
    generator.writeFieldName("name");
    generator.writeString(value.getName());
    generator.writeEndObject();
  }
}

Remove 'standalone="yes"' from generated XML

If you make document dependent on DOCTYPE (e.g. use named entities) then it will stop being standalone, thus standalone="yes" won't be allowed in XML declaration.

However standalone XML can be used anywhere, while non-standalone is problematic for XML parsers that don't load externals.

I don't see how this declaration could be a problem, other than for interoperability with software that doesn't support XML, but some horrible regex soup.

Move UIView up when the keyboard appears in iOS

i just created a lightweight keyboard handler to follow keyboard frame.

Usage:

 self.keyboardHandler = [EDKeyboardHandler new];

  [self.keyboardHandler listenWithBlock:^(KeyboardInfo *model)
  {
    //adjust view positions according to keyboard position here
  }];

and the KeyboardInfo model has the following properties:

typedef enum : NSUInteger {
    KeyboardStatusDidShow,
    KeyboardStatusWillShow,
    KeyboardStatusDidHide,
    KeyboardStatusWillHide,
} KeyboardStatus;

@interface KeyboardInfo:NSObject

@property (nonatomic,readonly) NSTimeInterval animationDuration;
@property (nonatomic,readonly) CGRect keyboardFrame;
@property (nonatomic,readonly) NSInteger animationCurve;
@property (nonatomic,readonly) KeyboardStatus status;

@end

check GitHub project for details and cocoaPods integration.

"unmappable character for encoding" warning in Java

Use the "\uxxxx" escape format.

According to Wikipedia, the copyright symbol is unicode U+00A9 so your line should read:

String copyright = "\u00a9 2003-2008 My Company. All rights reserved.";

How can I count all the lines of code in a directory recursively?

Here's a flexible one using older Python (works in at least Python 2.6) incorporating Shizzmo's lovely one-liner. Just fill in the types list with the filetypes you want counted in the source folder, and let it fly:

#!/usr/bin/python

import subprocess

rcmd = "( find ./ -name '*.%s' -print0 | xargs -0 cat ) | wc -l"
types = ['c','cpp','h','txt']

sum = 0
for el in types:
    cmd = rcmd % (el)
    p = subprocess.Popen([cmd],stdout=subprocess.PIPE,shell=True)
    out = p.stdout.read().strip()
    print "*.%s: %s" % (el,out)
    sum += int(out)
print "sum: %d" % (sum)

How can I make a weak protocol reference in 'pure' Swift (without @objc)

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

How to retrieve raw post data from HttpServletRequest in java

The request body is available as byte stream by HttpServletRequest#getInputStream():

InputStream body = request.getInputStream();
// ...

Or as character stream by HttpServletRequest#getReader():

Reader body = request.getReader();
// ...

Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

Adding Image to xCode by dragging it from File

For xCode 10, first you need to add the image in your assetsCatalogue and then type this:

let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))

For beginners, let imageView is the name of the UIImageView object we are about to create.

An example for embedding an image into a viewControler file would look like this:

import UIKit

class TutorialViewCotroller: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
        view.addSubview(imageView)
    }
}

Please notice that I did not use any extension for the image file name, as in my case it is a group of images.

How to open VMDK File of the Google-Chrome-OS bundle 2012?

Create a new Virtual machine in Virtual box, Select OS type Other and version Other/Unknown

On the Virtual Hard Disk screen, select "Use existing hard disk" and enter the path to the VMDK file.

It should boot your Chrome OS just fine.... BTW Chrome OS goes from VBOX bios screen to login in 7 seconds on my system!!!

Posting form to different MVC post action depending on the clicked submit button

BEST ANSWER 1:

ActionNameSelectorAttribute mentioned in

  1. How do you handle multiple submit buttons in ASP.NET MVC Framework?

  2. ASP.Net MVC 4 Form with 2 submit buttons/actions

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

ANSWER 2

Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor

Second Approach

Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

Third Approach: Client Script

<button name="ClientCancel" type="button" 
    onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" 
style="display:none;"></a>

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

Proper MIME type for .woff2 fonts

font/woff2

For nginx add the following to the mime.types file:

font/woff2 woff2;


Old Answer

The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2.

Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2 is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/* (font/ttf, font/woff2 etc)...

N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.

How to add a single item to a Pandas Series

  • ser1 = pd.Sereis(np.linspace(1, 10, 2))
  • element = np.nan
  • ser1 = ser1.append(pd.Series(element))

what is Ljava.lang.String;@

According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:

FieldType term | Type      | Interpretation
-------------- | --------- | --------------
L ClassName ;  | reference | an instance of class ClassName
[              | reference | one array dimension
...            | ...       | ...

the expression [Ljava.lang.String;@45a877 means this is an array ( [ ) of class java.lang.String ( Ljava.lang.String; ). And @45a877 is the address where the String object is stored in memory.

getting "No column was specified for column 2 of 'd'" in sql server cte?

Because you are creatin a table expression, you have to specify the structure of that table, you can achive this on two way:

1: In the select you can use the original columnnames (as in your first example), but with aggregates you have to use an alias (also in conflicting names). Like

sum(totalitems) as bkdqty

2: You need to specify the column names rigth after the name of the talbe, and then you just have to take care that the count of the names should mach the number of coulms was selected in the query. Like:

d (duration, bkdqty) 
AS (Select.... ) 

With the second solution both of your query will work!

How can I specify system properties in Tomcat configuration on startup?

You could add necessary properties to catalina.properties file in <tomcat installation directory>/conf directory.

Reference: https://tomcat.apache.org/tomcat-8.0-doc/config/index.html

All system properties are available including those set using the -D syntax, those automatically made available by the JVM and those configured in the $CATALINA_BASE/conf/catalina.properties file.

Different ways of adding to Dictionary

To answer the question first we need to take a look at the purpose of a dictionary and underlying technology.

Dictionary is the list of KeyValuePair<Tkey, Tvalue> where each value is represented by its unique key. Let's say we have a list of your favorite foods. Each value (food name) is represented by its unique key (a position = how much you like this food).

Example code:

Dictionary<int, string> myDietFavorites = new Dictionary<int, string>()
{
    { 1, "Burger"},
    { 2, "Fries"},
    { 3, "Donuts"}
};

Let's say you want to stay healthy, you've changed your mind and you want to replace your favorite "Burger" with salad. Your list is still a list of your favorites, you won't change the nature of the list. Your favorite will remain number one on the list, only it's value will change. This is when you call this:

/*your key stays 1, you only replace the value assigned to this key
  you alter existing record in your dictionary*/
myDietFavorites[1] = "Salad";

But don't forget you're the programmer, and from now on you finishes your sentences with ; you refuse to use emojis because they would throw compilation error and all list of favorites is 0 index based.

Your diet changed too! So you alter your list again:

/*you don't want to replace Salad, you want to add this new fancy 0
  position to your list. It wasn't there before so you can either define it*/
myDietFavorites[0] = "Pizza";

/*or Add it*/
myDietFavorites.Add(0, "Pizza");

There are two possibilities with defining, you either want to give a new definition for something not existent before or you want to change definition which already exists.

Add method allows you to add a record but only under one condition: key for this definition may not exist in your dictionary.

Now we are going to look under the hood. When you are making a dictionary your compiler make a reservation for the bucket (spaces in memory to store your records). Bucket don't store keys in the way you define them. Each key is hashed before going to the bucket (defined by Microsoft), worth mention that value part stays unchanged.

I'll use the CRC32 hashing algorithm to simplify my example. When you defining:

myDietFavorites[0] = "Pizza";

What is going to the bucket is db2dc565 "Pizza" (simplified).

When you alter the value in with:

myDietFavorites[0] = "Spaghetti";

You hash your 0 which is again db2dc565 then you look up this value in your bucket to find if it's there. If it's there you simply rewrite the value assigned to the key. If it's not there you'll place your value in the bucket.

When you calling Add function on your dictionary like:

myDietFavorite.Add(0, "Chocolate");

You hash your 0 to compare it's value to ones in the bucket. You may place it in the bucket only if it's not there.

It's crucial to know how it works especially if you work with dictionaries of string or char type of key. It's case sensitive because of undergoing hashing. So for example "name" != "Name". Let's use our CRC32 to depict this.

Value for "name" is: e04112b1 Value for "Name" is: 1107fb5b

Your password does not satisfy the current policy requirements

NOTE: This might not be a secure solution. But if you are working on a test environment, just need a quick fix and doesn't even care about the security settings. This is a quick solution.

The same issue happened to me when I ran "mysql_secure_installation" and modified password security level to 'medium'.

I bypassed the error by running the followings:

mysql -h localhost -u root -p
mysql>uninstall plugin validate_password;

make sure you reinstall the plugin "validate_password" if necessary.

Display a message in Visual Studio's output window when not debug mode?

The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).

This works with Debug.WriteLine and Console.WriteLine.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I solve my problem by passing nil permission while login.

[FBSession openActiveSessionWithReadPermissions:nil
                                       allowLoginUI:YES
                                  completionHandler:

Is Java's assertEquals method reliable?

public class StringEqualityTest extends TestCase {
    public void testEquality() throws Exception {
        String a = "abcde";
        String b = new String(a);
        assertTrue(a.equals(b));
        assertFalse(a == b);
        assertEquals(a, b);
    }
}

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

How to Populate a DataTable from a Stored Procedure

Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:

using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();

            da.Fill(dt);
        }
    }
}

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

How to use Google fonts in React.js?

In some cases your font resource maybe somewhere in your project directory. So you can load it like this using SCSS

 $list: (
      "Black",
      "BlackItalic",
      "Bold",
      "BoldItalic",
      "Italic",
      "Light",
      "LightItalic",
      "Medium",
      "MediumItalic",
      "Regular",
      "Thin",
      "ThinItalic"
    );
    
    @mixin setRobotoFonts {
      @each $var in $list {
        @font-face {
          font-family: "Roboto-#{$var}";
          src: url("../fonts/Roboto-#{$var}.ttf") format("ttf");
        }
      }
    }
@include setRobotoFonts();

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I just received the same error.

The strange thing is that commented the credential lines

// ->setUsername(self::$config->username)
// ->setPassword(self::$config->password)

And the problem disappeared.

I'm puzzled because the mail server definitely needs those credentials.

What is the difference between a JavaBean and a POJO?

A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See JavaBeans Conventions for more details.

A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.

How to read an external local JSON file in JavaScript?

I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:

// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) => 
  new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = resolve;
    request.onerror = reject;
    request.overrideMimeType("application/json");
    request.open(options.method, file, true);
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === "200") {
            resolve(request.responseText);
        }
    };
    request.send(null);
});

You can call it like this:

readFileP('<path to file>')
    .then(d => {
      '<do something with the response data in d.srcElement.response>'
    });

How to make inline functions in C#

Yes.

You can create anonymous methods or lambda expressions:

Func<string, string> PrefixTrimmer = delegate(string x) {
    return x ?? "";
};
Func<string, string> PrefixTrimmer = x => x ?? "";

Bash or KornShell (ksh)?

Bash is the standard for Linux.
My experience is that it is easier to find help for bash than for ksh or csh.

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

How do I save JSON to local text file

It's my solution to save local data to txt file.

_x000D_
_x000D_
function export2txt() {_x000D_
  const originalData = {_x000D_
    members: [{_x000D_
        name: "cliff",_x000D_
        age: "34"_x000D_
      },_x000D_
      {_x000D_
        name: "ted",_x000D_
        age: "42"_x000D_
      },_x000D_
      {_x000D_
        name: "bob",_x000D_
        age: "12"_x000D_
      }_x000D_
    ]_x000D_
  };_x000D_
_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {_x000D_
    type: "text/plain"_x000D_
  }));_x000D_
  a.setAttribute("download", "data.txt");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2txt()">Export data to local txt file</button>
_x000D_
_x000D_
_x000D_

How can I tell gcc not to inline a function?

I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline)) answer, as well as the asm("") answer. Neither one solved the problem.

Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.

This is sort of a dirty trick, but it works.

How to create an array for JSON using PHP?

also for array you can use short annotattion:

$arr = [
    [
        "region" => "valore",
        "price" => "valore2"
    ],
    [
        "region" => "valore",
        "price" => "valore2"
    ],
    [
        "region" => "valore",
        "price" => "valore2"
    ]
];

echo json_encode($arr);

How does the data-toggle attribute work? (What's its API?)

The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked

Note: the target element must have the appropriate class for bootstrap to carry out the action

Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv

Target:
class=collapse //I can collapse
id=myDiv

This is same for other type of toggle actions like tab, modal, dropdown

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

List only stopped Docker containers

Only stopped containers can be listed using:

docker ps --filter "status=exited"

or

docker ps -f "status=exited"

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

How do I insert values into a Map<K, V>?

Try this code

HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");

Specifying Font and Size in HTML table

The font tag has been deprecated for some time now.

That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.

And as @Alex H said, you should be using CSS for this.

Loop through files in a folder using VBA?

The Dir function is the way to go, but the problem is that you cannot use the Dir function recursively, as stated here, towards the bottom.

The way that I've handled this is to use the Dir function to get all of the sub-folders for the target folder and load them into an array, then pass the array into a function that recurses.

Here's a class that I wrote that accomplishes this, it includes the ability to search for filters. (You'll have to forgive the Hungarian Notation, this was written when it was all the rage.)

Private m_asFilters() As String
Private m_asFiles As Variant
Private m_lNext As Long
Private m_lMax As Long

Public Function GetFileList(ByVal ParentDir As String, Optional ByVal sSearch As String, Optional ByVal Deep As Boolean = True) As Variant
    m_lNext = 0
    m_lMax = 0

    ReDim m_asFiles(0)
    If Len(sSearch) Then
        m_asFilters() = Split(sSearch, "|")
    Else
        ReDim m_asFilters(0)
    End If

    If Deep Then
        Call RecursiveAddFiles(ParentDir)
    Else
        Call AddFiles(ParentDir)
    End If

    If m_lNext Then
        ReDim Preserve m_asFiles(m_lNext - 1)
        GetFileList = m_asFiles
    End If

End Function

Private Sub RecursiveAddFiles(ByVal ParentDir As String)
    Dim asDirs() As String
    Dim l As Long
    On Error GoTo ErrRecursiveAddFiles
    'Add the files in 'this' directory!


    Call AddFiles(ParentDir)

    ReDim asDirs(-1 To -1)
    asDirs = GetDirList(ParentDir)
    For l = 0 To UBound(asDirs)
        Call RecursiveAddFiles(asDirs(l))
    Next l
    On Error GoTo 0
Exit Sub
ErrRecursiveAddFiles:
End Sub
Private Function GetDirList(ByVal ParentDir As String) As String()
    Dim sDir As String
    Dim asRet() As String
    Dim l As Long
    Dim lMax As Long

    If Right(ParentDir, 1) <> "\" Then
        ParentDir = ParentDir & "\"
    End If
    sDir = Dir(ParentDir, vbDirectory Or vbHidden Or vbSystem)
    Do While Len(sDir)
        If GetAttr(ParentDir & sDir) And vbDirectory Then
            If Not (sDir = "." Or sDir = "..") Then
                If l >= lMax Then
                    lMax = lMax + 10
                    ReDim Preserve asRet(lMax)
                End If
                asRet(l) = ParentDir & sDir
                l = l + 1
            End If
        End If
        sDir = Dir
    Loop
    If l Then
        ReDim Preserve asRet(l - 1)
        GetDirList = asRet()
    End If
End Function
Private Sub AddFiles(ByVal ParentDir As String)
    Dim sFile As String
    Dim l As Long

    If Right(ParentDir, 1) <> "\" Then
        ParentDir = ParentDir & "\"
    End If

    For l = 0 To UBound(m_asFilters)
        sFile = Dir(ParentDir & "\" & m_asFilters(l), vbArchive Or vbHidden Or vbNormal Or vbReadOnly Or vbSystem)
        Do While Len(sFile)
            If Not (sFile = "." Or sFile = "..") Then
                If m_lNext >= m_lMax Then
                    m_lMax = m_lMax + 100
                    ReDim Preserve m_asFiles(m_lMax)
                End If
                m_asFiles(m_lNext) = ParentDir & sFile
                m_lNext = m_lNext + 1
            End If
            sFile = Dir
        Loop
    Next l
End Sub

where is gacutil.exe?

You can use the version in Windows SDK but sometimes it might not be the same version of the .NET Framework your using, getting you the following error:

Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

In .NET 4.0 you'll need to search inside Microsoft SDK v8.0A, e.g.: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (in my case I only have the 32 bit version installed by Visual Studio 2012).

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:

python -V

I hope it helps

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

No module named setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

displaying a string on the textview when clicking a button in android

Try this

public void onClick(View view){
    txtView.setText("hello");

    //printmyname();
    Toast.makeText(NameonbuttonclickActivity.this, "hello", Toast.LENGTH_LONG).show();
}

Also in toast use "Hello"

Difference between declaring variables before or in loop?

The following is what I wrote and compiled in .NET.

double r0;
for (int i = 0; i < 1000; i++) {
    r0 = i*i;
    Console.WriteLine(r0);
}

for (int j = 0; j < 1000; j++) {
    double r1 = j*j;
    Console.WriteLine(r1);
}

This is what I get from .NET Reflector when CIL is rendered back into code.

for (int i = 0; i < 0x3e8; i++)
{
    double r0 = i * i;
    Console.WriteLine(r0);
}
for (int j = 0; j < 0x3e8; j++)
{
    double r1 = j * j;
    Console.WriteLine(r1);
}

So both look exactly same after compilation. In managed languages code is converted into CL/byte code and at time of execution it's converted into machine language. So in machine language a double may not even be created on the stack. It may just be a register as code reflect that it is a temporary variable for WriteLine function. There are a whole set optimization rules just for loops. So the average guy shouldn't be worried about it, especially in managed languages. There are cases when you can optimize manage code, for example, if you have to concatenate a large number of strings using just string a; a+=anotherstring[i] vs using StringBuilder. There is very big difference in performance between both. There are a lot of such cases where the compiler cannot optimize your code, because it cannot figure out what is intended in a bigger scope. But it can pretty much optimize basic things for you.

How do you change the launcher logo of an app in Android Studio?

Look in the application's AndroidManifest.xml file for the <application> tag.

This application tag has an android:icon attribute, which is usually @drawable/ic_launcher. The value here is the name of the launcher icon file. If the value is @drawable/ic_launcher, then the name of the icon is ic_launcher.png.

Find this icon in your resource folders (res/mipmap-mdpi, res/mipmap-hdpi, etc.) and replace it.

A note on mipmap resources: If your launcher icon is currently in drawable folders such as res/drawable-hdpi, you should move them to the mipmap equivalents (e.g. res/mipmap-hdpi). Android will better preserve the resolution of drawables in the mipmap folder for display in launcher applications.

Android Studio note: If you are using Android Studio you can let studio place the drawables in the correct place for you. Simply right click on your application module and click New -> Image Asset.

For the icon type select either "Launcher Icons (Legacy Only)" for flat PNG files or "Launcher Icons (Adaptive and Legacy)" if you also want to generate an adaptive icon for API 26+ devices.

Retrieve version from maven pom.xml in code

If you use mvn packaging such as jar or war, use:

getClass().getPackage().getImplementationVersion()

It reads a property "Implementation-Version" of the generated META-INF/MANIFEST.MF (that is set to the pom.xml's version) in the archive.

Regex Match all characters between two strings

Here is how I did it:
This was easier for me than trying to figure out the specific regex necessary.

int indexPictureData = result.IndexOf("-PictureData:");
int indexIdentity = result.IndexOf("-Identity:");
string returnValue = result.Remove(indexPictureData + 13);
returnValue = returnValue + " [bytecoderemoved] " + result.Remove(0, indexIdentity); ` 

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a tblTest Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

The above query checks the existence of the tblTest table across all the schemas in the current database. Instead of this if you want to check the existence of the Table in a specified Schema and the Specified Database then we can write the above query as below:

IF EXISTS (SELECT * FROM Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a tblTest Table exists in the current database.

IF OBJECT_ID(N'dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Specifying the Database Name and Schema Name parts for the Table Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the table in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that even though the current database is MASTER database, we can check the existence of the tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Pros: Easy to remember. One other notable point to mention about OBJECT_ID() function is: it provides an option to check the existence of the Temporary Table which is created in the current connection context. All other Approaches checks the existence of the Temporary Table created across all the connections context instead of just the current connection context. Below query shows how to check the existence of a Temporary Table using OBJECT_ID() function:

CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END
GO

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.tblTest') AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'tblTest' AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per [Microsoft BOL][1] link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'tblTest' AND xtype = N'U')
BEGIN
  PRINT 'Table Exists'
END

Reference: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

Change the row color in DataGridView based on the quantity of a cell value

Just remove the : in your Quantity. Make sure that your attribute is the same with the parameter you include in the code, like this:

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
        If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
            Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
        End If
    Next
End Sub

What is the canonical way to trim a string in Ruby without creating a new string?

There's no need to both strip and chomp as strip will also remove trailing carriage returns - unless you've changed the default record separator and that's what you're chomping.

Olly's answer already has the canonical way of doing this in Ruby, though if you find yourself doing this a lot you could always define a method for it:

def strip_or_self!(str)
  str.strip! || str
end

Giving:

@title = strip_or_self!(tokens[Title]) if tokens[Title]

Also keep in mind that the if statement will prevent @title from being assigned if the token is nil, which will result in it keeping its previous value. If you want or don't mind @title always being assigned you can move the check into the method and further reduce duplication:

def strip_or_self!(str)
  str.strip! || str if str
end

As an alternative, if you're feeling adventurous you can define a method on String itself:

class String
  def strip_or_self!
    strip! || self
  end
end

Giving one of:

@title = tokens[Title].strip_or_self! if tokens[Title]

@title = tokens[Title] && tokens[Title].strip_or_self!

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

Link vs compile vs controller

Compile :

This is the phase where Angular actually compiles your directive. This compile function is called just once for each references to the given directive. For example, say you are using the ng-repeat directive. ng-repeat will have to look up the element it is attached to, extract the html fragment that it is attached to and create a template function.

If you have used HandleBars, underscore templates or equivalent, its like compiling their templates to extract out a template function. To this template function you pass data and the return value of that function is the html with the data in the right places.

The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.

Linking phase :

The linking phase is where you attach the data ( $scope ) to the linking function and it should return you the linked html. Since the directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the data attached to it. In angular if you write code in the linking function its generally the post-link function (by default). It is kind of a callback that gets called after the linking function has linked the data with the template.

Controller :

The controller is a place where you put in some directive specific logic. This logic can go into the linking function as well, but then you would have to put that logic on the scope to make it "shareable". The problem with that is that you would then be corrupting the scope with your directives stuff which is not really something that is expected. So what is the alternative if two Directives want to talk to each other / co-operate with each other? Ofcourse you could put all that logic into a service and then make both these directives depend on that service but that just brings in one more dependency. The alternative is to provide a Controller for this scope ( usually isolate scope ? ) and then this controller is injected into another directive when that directive "requires" the other one. See tabs and panes on the first page of angularjs.org for an example.

Wavy shape with css

My implementation uses the svg element in html and I also made a generator for making the wave you want:

https://smooth.ie/blogs/news/svg-wavey-transitions-between-sections

<div style="height: 150px; overflow: hidden;">
  <svg viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;">
    <path d="M0.00,92.27 C216.83,192.92 304.30,8.39 500.00,109.03 L500.00,0.00 L0.00,0.00 Z" style="stroke: none;fill: #e1efe3;"></path>
  </svg>
</div>

https://jsfiddle.net/1b8L7nax/5/

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Copied from the stacktrace:

BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()

By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib has a constructor with a SessionFactory argument. By adding the @Autowired annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory in your case, and provide it as a constructor argument, e.g.

@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
    // ...
}

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

I had the exact same problem in a project. The issue is that even though the fetch size might be small enough, the JDBCTemplate reads all the result of your query and maps it out in a huge list which might blow your memory. I ended up extending NamedParameterJdbcTemplate to create a function which returns a Stream of Object. That Stream is based on the ResultSet normally returned by JDBC but will pull data from the ResultSet only as the Stream requires it. This will work if you don't keep a reference of all the Object this Stream spits. I did inspire myself a lot on the implementation of org.springframework.jdbc.core.JdbcTemplate#execute(org.springframework.jdbc.core.ConnectionCallback). The only real difference has to do with what to do with the ResultSet. I ended up writing this function to wrap up the ResultSet:

private <T> Stream<T> wrapIntoStream(ResultSet rs, RowMapper<T> mapper) {
    CustomSpliterator<T> spliterator = new CustomSpliterator<T>(rs, mapper, Long.MAX_VALUE, NON-NULL | IMMUTABLE | ORDERED);
    Stream<T> stream = StreamSupport.stream(spliterator, false);
    return stream;
}
private static class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
    // won't put code for constructor or properties here
    // the idea is to pull for the ResultSet and set into the Stream
    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            // you can add some logic to close the stream/Resultset automatically
            if(rs.next()) {
                T mapped = mapper.mapRow(rs, rowNumber++);
                action.accept(mapped);
                return true;
            } else {
                return false;
            }
        } catch (SQLException) {
            // do something with this Exception
        }
    }
}

you can add some logic to make that Stream "auto closable", otherwise don't forget to close it when you are done.

.jar error - could not find or load main class

I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.

What is a tracking branch?

The Pro Git book mentions:

Tracking branches are local branches that have a direct relationship to a remote branch

Not exactly. The SO question "Having a hard time understanding git-fetch" includes:

There's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo.

But actually, once you establish an upstream branch relationship between:

  • a local branch like master
  • and a remote tracking branch like origin/master

Then you can consider master as a local tracking branch: It tracks the remote tracking branch origin/master which, in turn, tracks the master branch of the upstream repo origin.

alt text

What are the differences between json and simplejson Python modules?

All of these answers aren't very helpful because they are time sensitive.

After doing some research of my own I found that simplejson is indeed faster than the builtin, if you keep it updated to the latest version.

pip/easy_install wanted to install 2.3.2 on ubuntu 12.04, but after finding out the latest simplejson version is actually 3.3.0, so I updated it and reran the time tests.

  • simplejson is about 3x faster than the builtin json at loads
  • simplejson is about 30% faster than the builtin json at dumps

Disclaimer:

The above statements are in python-2.7.3 and simplejson 3.3.0 (with c speedups) And to make sure my answer also isn't time sensitive, you should run your own tests to check since it varies so much between versions; there's no easy answer that isn't time sensitive.

How to tell if C speedups are enabled in simplejson:

import simplejson
# If this is True, then c speedups are enabled.
print bool(getattr(simplejson, '_speedups', False))

UPDATE: I recently came across a library called ujson that is performing ~3x faster than simplejson with some basic tests.

Angular - Use pipes in services and components

As of Angular 6 you can import formatDate from @angular/common utility to use inside the components.

It was intruduced at https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4ae

I can be used as:

import {formatDate} from '@angular/common';
formatDate(new Date(), 'd MMM yy HH:mm', 'en');

Although the locale has to be supplied

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

Input size vs width

You can use both. The css style will override the size attribute in browsers that support CSS and make the field the correct width, and for those that don't, it will fall back to the specified number of characters.

Edit: I should have mentioned that the size attribute isn't a precise method of sizing: according to the HTML specification, it should refer to the number of characters of the current font the input will be able to display at once.

However, unless the font specified is a fixed-width/monospace font, this is not a guarantee that the specified number of characters will actually be visible; in most fonts, different characters will be different widths. This question has some good answers relating to this issue.

The snippet below demonstrates both approaches.

_x000D_
_x000D_
@font-face {_x000D_
    font-family: 'Diplomata';_x000D_
    font-style: normal;_x000D_
    font-weight: 400;_x000D_
    src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');_x000D_
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
@font-face {_x000D_
    font-family: 'Open Sans Condensed';_x000D_
    font-style: normal;_x000D_
    font-weight: 300;_x000D_
    src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2');_x000D_
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
p {_x000D_
  margin: 0 0 10px 0;_x000D_
}_x000D_
input {_x000D_
  font-size: 20px;_x000D_
}_x000D_
.narrow-font {_x000D_
  font-family: 'Open Sans Condensed', sans-serif;_x000D_
}_x000D_
.wide-font {_x000D_
  font-family: 'Diplomata', cursive;_x000D_
}_x000D_
.set-width {_x000D_
  width: 220px;_x000D_
}
_x000D_
<p>_x000D_
  <input type="text" size="10" class="narrow-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="wide-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="narrow-font set-width" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="wide-font set-width" value="0123456789" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I faced this issue with Eclipse (Version: 2019-12 (4.14.0)) too. The solution seems either to use IntelliJ or to use the Maven test to run such tests in Eclipse.

What is the difference between HTTP and REST?

As I understand it, REST enforces the use of the available HTTP commands as they were meant to be used.

For example, I could do:

GET
http://example.com?method=delete&item=xxx

But with rest I would use the "DELETE" request method, removing the need for the "method" query param

DELETE
http://example.com?item=xxx

How to get element by classname or id

getElementsByClassName is a function on the DOM Document. It is neither a jQuery nor a jqLite function.

Don't add the period before the class name when using it:

var result = document.getElementsByClassName("multi-files");

Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):

var wrappedResult = angular.element(result);

If you want to select from the element in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0] instead of element:

link: function (scope, element, attrs) {

  var elementResult = element[0].getElementsByClassName('multi-files');
}

Alternatively you can use the document.querySelector function (need the period here if selecting by class):

var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);

Demo: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=preview

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

What’s the best way to load a JSONObject from a json text file?

Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

import org.json.JSONObject;
public class JSONParsing {
    public static void main(String[] args) throws Exception {
        File f = new File("file.json");
        if (f.exists()){
            InputStream is = new FileInputStream("file.json");
            String jsonTxt = IOUtils.toString(is, "UTF-8");
            System.out.println(jsonTxt);
            JSONObject json = new JSONObject(jsonTxt);       
            String a = json.getString("1000");
            System.out.println(a);   
        }
    }
}

I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

Insert current date/time using now() in a field using MySQL/PHP

What about SYSDATE() ?

<?php
  $db = mysql_connect('localhost','user','pass');
  mysql_select_db('test_db');

  $stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}','{$last}','SYSDATE())";
  $rslt = mysql_query($stmt);
?>

Look at Difference between NOW(), SYSDATE() & CURRENT_DATE() in MySQL for more info about NOW() and SYSDATE().

LDAP filter for blank (empty) attribute

From LDAP, there is not a query method to determine an empty string.

The best practice would be to scrub your data inputs to LDAP as an empty or null value in LDAP is no value at all.

To determine this you would need to query for all with a value (manager=*) and then use code to determine the ones that were a "space" or null value.

And as Terry said, storing an empty or null value in an attribute of DN syntax is wrong.

Some LDAP server implementations will not permit entering a DN where the DN entry does not exist.

Perhaps, you could, if your DN's are consistent, use something like:

(&(!(manager=cn*))(manager=*))

This should return any value of manager where there was a value for manager and it did not start with "cn".

However, some LDAP implementations will not allow sub-string searches on DN syntax attributes.

-jim

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

My five cents:

Both direction array of integers function.

When range(0, 5) become [0, 1, 2, 3, 4, 5].

And range(5, 0) become [5, 4, 3, 2, 1, 0].

Based on this answer.

function range(start, end) {
  const isReverse = (start > end);
  const targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1;
  const arr = new Array(targetLength);
  const b = Array.apply(null, arr);
  const result = b.map((discard, n) => {
    return (isReverse) ? n + end : n + start;
  });

  return (isReverse) ? result.reverse() : result;
}

P.S. For use in real life you should also check args for isFinite() and isNaN().

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

How to center a WPF app on screen?

There is no WPF equivalent. System.Windows.Forms.Screen is still part of the .NET framework and can be used from WPF though.

See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper class to wrap your WPF control.

PHP7 : install ext-dom issue

simply run

sudo apt install php-xml

its worked for me

JavaScript Infinitely Looping slideshow with delays?

Here's a nice, tidy solution for you: (also see the live demo ->)

window.onload = function start() {
    slide();
}

function slide() {
    var currMarg = 0,
        contStyle = document.getElementById('container').style;
    setInterval(function() {
        currMarg = currMarg == 1800 ? 0 : currMarg + 600;
        contStyle.marginLeft = '-' + currMarg + 'px';
    }, 3000);
}

Since you are trying to learn, allow me to explain how this works.

First we declare two variables: currMarg and contStyle. currMarg is an integer that we will use to track/update what left margin the container should have. We declare it outside the actual update function (in a closure), so that it can be continuously updated/access without losing its value. contStyle is simply a convenience variable that gives us access to the containers styles without having to locate the element on each interval.

Next, we will use setInterval to establish a function which should be called every 3 seconds, until we tell it to stop (there's your infinite loop, without freezing the browser). It works exactly like setTimeout, except it happens infinitely until cancelled, instead of just happening once.

We pass an anonymous function to setInterval, which will do our work for us. The first line is:

currMarg = currMarg == 1800 ? 0 : currMarg + 600;

This is a ternary operator. It will assign currMarg the value of 0 if currMarg is equal to 1800, otherwise it will increment currMarg by 600.

With the second line, we simply assign our chosen value to containers marginLeft, and we're done!

Note: For the demo, I changed the negative values to positive, so the effect would be visible.

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.

Edit

Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

How to capture a JFrame's close button click event?

This may work:

jdialog.addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        System.out.println("jdialog window closed event received");
    }

    public void windowClosing(WindowEvent e) {
        System.out.println("jdialog window closing event received");
    }
});

Source: https://alvinalexander.com/java/jdialog-close-closing-event

Executing Shell Scripts from the OS X Dock?

In the Script Editor:

do shell script "/full/path/to/your/script -with 'all desired args'"

Save as an application bundle.

As long as all you want to do is get the effect of the script, this will work fine. You won't see STDOUT or STDERR.

How to break out of the IF statement

In this case, insert a single else:

public void Method()
{
    if(something)
    {
        // some code
        if(something2)
        {
            // now I should break from ifs and go to te code outside ifs
        }
        else return;
    }
    // The code i want to go if the second if is true
}

Generally: There is no break in an if/else sequence, simply arrange your code correctly in if / if else / else clauses.

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

How to upload a project to Github

  1. First You have to create an account on Github
  2. Then create new Project - name that Project as you want then your project url is shown
  3. Now copy the url
  4. Then open Command Prompt and go to the directory or folder which you want to upload using cmd
  5. Then type the following Commands

     git init
     git add .
     git commit -m "initial commit"
     git remote add origin PASTE URL
     git push -u origin master
    
  6. Now check your GitHub account, Repository is successfully uploaded.

For Complete guidance, you can watch this video.

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Storing a file in a database as opposed to the file system?

I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems.

Object cannot be cast from DBNull to other types

For others that arrive on this page from google:

DataRow also has a function .IsNull("ColumnName")

    public DateTime? TestDt; 
    public Parse(DataRow row)
    {
        if (!row.IsNull("TEST_DT"))
            TestDt = Convert.ToDateTime(row["TEST_DT"]);
    }

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Same thing with gcc version 4.8.1 (GCC) and libstdc++.so.6.0.18. Had to copy it here /usr/lib/x86_64-linux-gnu on my ubuntu box.

Send inline image in email

An even more minimalistic example:

var linkedResource = new LinkedResource(@"C:\Image.jpg", MediaTypeNames.Image.Jpeg);

// My mail provider would not accept an email with only an image, adding hello so that the content looks less suspicious.
var htmlBody = $"hello<img src=\"cid:{linkedResource.ContentId}\"/>";
var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(linkedResource);

var mailMessage = new MailMessage
{
    From = new MailAddress("[email protected]"),
    To = { "[email protected]" },
    Subject = "yourSubject",
    AlternateViews = { alternateView }
};

var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);

What is a non-capturing group in regular expressions?

Well I am a JavaScript developer and will try to explain its significance pertaining to JavaScript.

Consider a scenario where you want to match cat is animal when you would like match cat and animal and both should have a is in between them.

 // this will ignore "is" as that's is what we want
"cat is animal".match(/(cat)(?: is )(animal)/) ;
result ["cat is animal", "cat", "animal"]

 // using lookahead pattern it will match only "cat" we can
 // use lookahead but the problem is we can not give anything
 // at the back of lookahead pattern
"cat is animal".match(/cat(?= is animal)/) ;
result ["cat"]

 //so I gave another grouping parenthesis for animal
 // in lookahead pattern to match animal as well
"cat is animal".match(/(cat)(?= is (animal))/) ;
result ["cat", "cat", "animal"]

 // we got extra cat in above example so removing another grouping
"cat is animal".match(/cat(?= is (animal))/) ;
result ["cat", "animal"]

Calculate number of hours between 2 dates in PHP

This function helps you to calculate exact years and months between two given dates, $doj1 and $doj. It returns example 4.3 means 4 years and 3 month.

<?php
    function cal_exp($doj1)
    {
        $doj1=strtotime($doj1);
        $doj=date("m/d/Y",$doj1); //till date or any given date

        $now=date("m/d/Y");
        //$b=strtotime($b1);
        //echo $c=$b1-$a2;
        //echo date("Y-m-d H:i:s",$c);
        $year=date("Y");
        //$chk_leap=is_leapyear($year);

        //$year_diff=365.25;

        $x=explode("/",$doj);
        $y1=explode("/",$now);

        $yy=$x[2];
        $mm=$x[0];
        $dd=$x[1];

        $yy1=$y1[2];
        $mm1=$y1[0];
        $dd1=$y1[1];
        $mn=0;
        $mn1=0;
        $ye=0;
        if($mm1>$mm)
        {
            $mn=$mm1-$mm;
            if($dd1<$dd)
            {
                $mn=$mn-1;
            }
            $ye=$yy1-$yy;
        }
        else if($mm1<$mm)
        {
            $mn=12-$mm;
            //$mn=$mn;

            if($mm!=1)
            {
                $mn1=$mm1-1;
            }

            $mn+=$mn1;
            if($dd1>$dd)
            {
                $mn+=1;
            }

            $yy=$yy+1;
            $ye=$yy1-$yy;
        }
        else
        {
            $ye=$yy1-$yy;
            $ye=$ye-1;

            $mn=12-1;

            if($dd1>$dd)
            {
                $ye+=1;
                $mn=0;
            }
        }

        $to=$ye." year and ".$mn." months";
        return $ye.".".$mn;

        /*return daysDiff($x[2],$x[0],$x[1]);
         $days=dateDiff("/",$now,$doj)/$year_diff;
        $days_exp=explode(".",$days);
        return $years_exp=$days; //number of years exp*/
    }
?>

DD/MM/YYYY Date format in Moment.js

This actually worked for me:

moment(mydate).format('L');

How to exit a 'git status' list in a terminal?

:q

that's a less command, actually. It uses the same commands as vi.

How to convert .pfx file to keystore with private key?

I found this page which tells you how to import a PFX to JKS (Java Key Store):

keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

This is how use SignarR in order to target a specific user (without using any provider):

 private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();

 public string Login(string username)
 {
     clients.TryAdd(Context.ConnectionId, username);            
     return username;
 }

// The variable 'contextIdClient' is equal to Context.ConnectionId of the user, 
// once logged in. You have to store that 'id' inside a dictionaty for example.  
Clients.Client(contextIdClient).send("Hello!");

Split an integer into digits to compute an ISBN checksum

Just assuming you want to get the i-th least significant digit from an integer number x, you can try:

(abs(x)%(10**i))/(10**(i-1))

I hope it helps.

How do I convert a String object into a Hash object?

I prefer to abuse ActiveSupport::JSON. Their approach is to convert the hash to yaml and then load it. Unfortunately the conversion to yaml isn't simple and you'd probably want to borrow it from AS if you don't have AS in your project already.

We also have to convert any symbols into regular string-keys as symbols aren't appropriate in JSON.

However, its unable to handle hashes that have a date string in them (our date strings end up not being surrounded by strings, which is where the big issue comes in):

string = '{'last_request_at' : 2011-12-28 23:00:00 UTC }' ActiveSupport::JSON.decode(string.gsub(/:([a-zA-z])/,'\\1').gsub('=>', ' : '))

Would result in an invalid JSON string error when it tries to parse the date value.

Would love any suggestions on how to handle this case

Submit two forms with one button

A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));

document.forms.payPal.submit();

how to execute php code within javascript

Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work

Build error: "The process cannot access the file because it is being used by another process"

I struggled with issue for 5 days and could get the source of the problem through Event Viewer Logs; Port 443, my application trying to access was in use, so I had to change the registry settings ; Basically you will b able to reach to source of issue thru error logs in event viewer.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

How can I switch themes in Visual Studio 2012

Also, you can use or create and share Visual Studio color schemes: https://studiostyl.es/

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

How to get all keys with their values in redis

Below is just a little variant of the script provided by @"Juuso Ohtonen".

I have add a password variable and counter so you can can check the progression of your backup. Also I replaced simple brackets [] by double brackets [[]] to prevent an error I had on macos.

1. Get the total number of keys

$ sudo redis-cli
INFO keyspace
AUTH yourpassword
INFO keyspace

2. Edit the script

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
PASS="yourpassword"
i=1
for key in $(redis-cli -a "$PASS" --scan --pattern "$REDIS_KEY_PATTERN")
do
    echo $i.
    ((i=i+1))
    type=$(redis-cli -a "$PASS" type $key)
    if [[ $type = "list" ]]
    then
        printf "$key => \n$(redis-cli -a "$PASS" lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [[ $type = "hash" ]]
    then
        printf "$key => \n$(redis-cli -a "$PASS" hgetall $key | sed 's/^/  /')\n"
    else
        printf "$key => $(redis-cli -a "$PASS" get $key)\n"
    fi
    echo
done

3. Execute the script

bash redis_print.sh > redis.bak

4. Check progression

tail redis.bak

How to use Boost in Visual Studio 2010

This thread has been around a while, and I thought I'd add something about HOW to build Boost as fast as possible on your specific hardware.

If you have a 4 or 6-core use -j5 or -j7 respectively. Certainly not the standard build nor -j2 unless you indeed have dual core.

I'm running a Sandy Bridge Extreme with stock clocked 3930K (6-core) on my main station, but have a 2600k (4-core) on older backup box, and the trend is I get the best Boost compile times with N + 1 build processes where N is the number of physical cores. N+2 reaches a point of diminishing returns and the times go up.

Notes: Hyperthreading is enabled, 32GB RAM DDR3, Samsung 840 EVO SSD.

-j7 on 6-core (2 minutes and 51 seconds) (Win7 Ultimate x64)(Visual Studio 2013)

PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j7 --build-type=complete msvc stage }

Days              : 0
Hours             : 0
Minutes           : 2
Seconds           : 51
Milliseconds      : 128
Ticks             : 1711281830
TotalDays         : 0.0019806502662037
TotalHours        : 0.0475356063888889
TotalMinutes      : 2.85213638333333
TotalSeconds      : 171.128183
TotalMilliseconds : 171128.183

-j6 on 6-core (3 minutes and 2 seconds) (Win7 Ultimate x64)(Visual Studio 2013)

PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j6 --build-type=complete msvc stage }

Days              : 0
Hours             : 0
Minutes           : 3
Seconds           : 2
Milliseconds      : 809
Ticks             : 1828093904
TotalDays         : 0.00211584942592593
TotalHours        : 0.0507803862222222
TotalMinutes      : 3.04682317333333
TotalSeconds      : 182.8093904
TotalMilliseconds : 182809.3904

-j8 on 6-core (3 minutes and 17 seconds) (Win7 Ultimate x64)(Visual Studio 2013)

PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j8 --build-type=complete msvc stage }

Days              : 0
Hours             : 0
Minutes           : 3
Seconds           : 17
Milliseconds      : 652
Ticks             : 1976523915
TotalDays         : 0.00228764342013889
TotalHours        : 0.0549034420833333
TotalMinutes      : 3.294206525
TotalSeconds      : 197.6523915
TotalMilliseconds : 197652.3915

-j7 build on 6-core

Config

Building the Boost C++ Libraries.


Performing configuration checks

    - 32-bit                   : yes (cached)
    - arm                      : no  (cached)
    - mips1                    : no  (cached)
    - power                    : no  (cached)
    - sparc                    : no  (cached)
    - x86                      : yes (cached)
    - has_icu builds           : no  (cached)
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
    - zlib                     : no  (cached)
    - iconv (libc)             : no  (cached)
    - iconv (separate)         : no  (cached)
    - icu                      : no  (cached)
    - icu (lib64)              : no  (cached)
    - message-compiler         : yes (cached)
    - compiler-supports-ssse3  : yes (cached)
    - compiler-supports-avx2   : yes (cached)
    - gcc visibility           : no  (cached)
    - long double support      : yes (cached)
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
    - zlib                     : no  (cached)

I note the 64-bit build takes a bit longer, I need to do the same comparison for those and update.

SQL statement to get column type

use this query

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TABLE_NAME'
ORDER BY ORDINAL_POSITION

Rotate and translate

The reason is because you are using the transform property twice. Due to CSS rules with the cascade, the last declaration wins if they have the same specificity. As both transform declarations are in the same rule set, this is the case.

What it is doing is this:

  1. rotate the text 90 degrees. Ok.
  2. translate 50% by 50%. Ok, this is same property as step one, so do this step and ignore step 1.

See http://jsfiddle.net/Lx76Y/ and open it in the debugger to see the first declaration overwritten

As the translate is overwriting the rotate, you have to combine them in the same declaration instead: http://jsfiddle.net/Lx76Y/1/

To do this you use a space separated list of transforms:

#rotatedtext {
    transform-origin: left;
    transform: translate(50%, 50%) rotate(90deg) ;
}

Remember that they are specified in a chain, so the translate is applied first, then the rotate after that.

Best way to save a trained model in PyTorch?

A common PyTorch convention is to save models using either a .pt or .pth file extension.

Save/Load Entire Model Save:

path = "username/directory/lstmmodelgpu.pth"
torch.save(trainer, path)

Load:

Model class must be defined somewhere

model = torch.load(PATH)
model.eval()

Open URL in same window and in same tab

Use this:

location.href = "http://example.com";

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with /> at the end. In React, we have to close every element. Your code should be:

<input id="icon_prefix" type="text" class="validate/">

Select first empty cell in column F starting from row 1. (without using offset )

If all you're trying to do is select the first blank cell in a given column, you can give this a try:

Code:

Public Sub SelectFirstBlankCell()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 6   'column F has a value of 6
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
        End If
    Next
End Sub

Before Selection - first blank cell to select:

enter image description here

After Selection:

enter image description here

Get google map link with latitude/longitude

See documentation on how to search using latitude/longitude here.

For location specified as: +38° 34' 24.00", -109° 32' 57.00

https://maps.google.com/maps?q=%2B38%C2%B0+34'+24.00%22,+-109%C2%B0+32'+57.00&ie=UTF-8

Note that the plus signs (%2B) and degree symbols(%C2%B0) need to be properly encoded.

How to use CMAKE_INSTALL_PREFIX

But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

My first week of using cmake - after some years of GNU autotools - so I am still learning (better then writing m4 macros), but I think modifying CMAKE_INSTALL_PREFIX after setting project is the better place.

CMakeLists.txt

cmake_minimum_required (VERSION 2.8)

set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
project (BarkBark)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")

First run (no cache)

CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- The C compiler identification is GNU 4.4.7
-- etc, etc,...
CIP = /usr/local (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Second run

CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Let me know if I am mistaken, I have a lot of learning to do. It's fun.

Android ListView selected item stay highlighted

From Avinash Kumar Pankaj's example

View v;

then at oncreate method

v = new View(getActivity());

and then onlistitemclick method i wrote

public void onListItemClick(ListView listView, View view, int position,
       long id) {
   v.setBackgroundResource(0);
   view.setBackgroundResource(R.color.green);
   v = view;
}

It worked for me. Thank you.

I replaced

v = new View(getActivity());

to

v = new View(this);

and the code worked well.

It is necessary the xml files 'colors' and 'bg_key' from previous examples too, as well as ListView attribute android:background="@drawable/bg_key"

Mauro

How can I specify a branch/tag when adding a Git submodule?

We use Quack to pull a specific module from another Git repository. We need to pull code without the whole code base of the provided repository - we need a very specific module / file from that huge repository and should be updated every time we run update.

So we achieved it in this way:

Create configuration

name: Project Name

modules:
  local/path:
    repository: https://github.com/<username>/<repo>.git
    path: repo/path
    branch: dev
  other/local/path/filename.txt:
    repository: https://github.com/<username>/<repo>.git
    hexsha: 9e3e9642cfea36f4ae216d27df100134920143b9
    path: repo/path/filename.txt

profiles:
  init:
    tasks: ['modules']

With the above configuration, it creates one directory from the provided GitHub repository as specified in first module configuration, and the other one is to pull and create a file from the given repository.

Other developers just need to run

$ quack

And it pulls the code from the above configurations.