Programs & Examples On #Sha 3

SHA-3 is a family of cryptographic hash functions, a successor to SHA-2.

Subtracting Number of Days from a Date in PL/SQL

Use sysdate-1 to subtract one day from system date.

select sysdate, sysdate -1 from dual;

Output:

SYSDATE  SYSDATE-1
-------- ---------
22-10-13 21-10-13 

How can I use a custom font in Java?

If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:

Oracle Java SE 6: java.awt.Font

There is a tutorial available from Oracle that shows this example:

try {
     GraphicsEnvironment ge = 
         GraphicsEnvironment.getLocalGraphicsEnvironment();
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
     //Handle exception
}

I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.

An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.

Get most recent row for given ID

Simple Way To Achieve

I know it's an old question You can also do something like

SELECT * FROM Table WHERE id=1 ORDER BY signin DESC

In above, query the first record will be the most recent record.

For only one record you can use something like

SELECT top(1) * FROM Table WHERE id=1 ORDER BY signin DESC

Above query will only return one latest record.

Cheers!

Windows batch files: .bat vs .cmd?

From this news group posting by Mark Zbikowski himself:

The differences between .CMD and .BAT as far as CMD.EXE is concerned are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL only on errors.

In other words, if ERRORLEVEL is set to non-0 and then you run one of those commands, the resulting ERRORLEVEL will be:

  • left alone at its non-0 value in a .bat file
  • reset to 0 in a .cmd file.

JWT authentication for ASP.NET Web API

Here's a very minimal and secure implementation of a Claims based Authentication using JWT token in an ASP.NET Core Web API.

first of all, you need to expose an endpoint that returns a JWT token with claims assigned to a user:

 /// <summary>
        /// Login provides API to verify user and returns authentication token.
        /// API Path:  api/account/login
        /// </summary>
        /// <param name="paramUser">Username and Password</param>
        /// <returns>{Token: [Token] }</returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] UserRequestVM paramUser, CancellationToken ct)
        {

            var result = await UserApplication.PasswordSignInAsync(paramUser.Email, paramUser.Password, false, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                UserRequestVM request = new UserRequestVM();
                request.Email = paramUser.Email;


                ApplicationUser UserDetails = await this.GetUserByEmail(request);
                List<ApplicationClaim> UserClaims = await this.ClaimApplication.GetListByUser(UserDetails);

                var Claims = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(JwtRegisteredClaimNames.Sub, paramUser.Email.ToString()),
                                    new Claim(UserId, UserDetails.UserId.ToString())
                                });


                //Adding UserClaims to JWT claims
                foreach (var item in UserClaims)
                {
                    Claims.AddClaim(new Claim(item.ClaimCode, string.Empty));
                }

                var tokenHandler = new JwtSecurityTokenHandler();
                  // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                var encryptionkey = Configuration["Jwt:Encryptionkey"];
                var key = Encoding.ASCII.GetBytes(encryptionkey);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer = Configuration["Jwt:Issuer"],
                    Subject = Claims,

                // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                    Expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["Jwt:ExpiryTimeInMinutes"])),

                    //algorithm to sign the token
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return Ok(new
                {
                    token = tokenString
                });
            }

            return BadRequest("Wrong Username or password");
        }

now you need to Add Authentication to your services in your ConfigureServices inside your startup.cs to add JWT authentication as your default authentication service like this:

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
             .AddJwtBearer(cfg =>
             {
                 cfg.RequireHttpsMetadata = false;
                 cfg.SaveToken = true;
                 cfg.TokenValidationParameters = new TokenValidationParameters()
                 {
                     //ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Encryptionkey"])),
                     ValidateAudience = false,
                     ValidateLifetime = true,
                     ValidIssuer = configuration["Jwt:Issuer"],
                     //ValidAudience = Configuration["Jwt:Audience"],
                     //IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"])),
                 };
             });

now you can add policies to your authorization services like this:

services.AddAuthorization(options =>
            {
                options.AddPolicy("YourPolicyNameHere",
                                policy => policy.RequireClaim("YourClaimNameHere"));
            });

ALTERNATIVELY, You can also (not necessary) populate all of your claims from your database as this will only run once on your application startup and add them to policies like this:

  services.AddAuthorization(async options =>
            {
                var ClaimList = await claimApplication.GetList(applicationClaim);
                foreach (var item in ClaimList)
                {                        
                    options.AddPolicy(item.ClaimCode, policy => policy.RequireClaim(item.ClaimCode));                       
                }
            });

now you can put the Policy filter on any of the methods that you want to be authorized like this:

 [HttpPost("update")]
        [Authorize(Policy = "ACC_UP")]
        public async Task<IActionResult> Update([FromBody] UserRequestVM requestVm, CancellationToken ct)
        {
//your logic goes here
}

Hope this helps

Mixing C# & VB In The Same Project

You can not mix vb and c# within the same project - if you notice in visual studio the project files are either .vbproj or .csproj. You can within a solution - have 1 proj in vb and 1 in c#.

Looks like according to this you can potentially use them both in a web project in the App_Code directory:

http://pietschsoft.com/post/2006/03/30/ASPNET-20-Use-VBNET-and-C-within-the-App_Code-folder.aspx

Clear text area

This works:

$('#textareaName').val('');

Merge DLL into EXE?

Here is the official documentation. This is also automatically downloaded at step 2.

Below is a really simple way to do it and I've successfully built my app using .NET framework 4.6.1

  1. Install ILMerge nuget package either via gui or commandline:

    Install-Package ilmerge
    
  2. Verify you have downloaded it. Now Install (not sure the command for this, but just go to your nuget packages): enter image description here Note: You probably only need to install it for one of your solutions if you have multiple

  3. Navigate to your solution folder and in the packages folder you should see 'ILMerge' with an executable:

    \FindMyiPhone-master\FindMyiPhone-master\packages\ILMerge.2.14.1208\tools
    

    enter image description here

  4. Now here is the executable which you could copy over to your \bin\Debug (or whereever your app is built) and then in commandline/powershell do something like below:

    ILMerge.exe myExecutable.exe myDll1.dll myDll2.dll myDlln.dll myNEWExecutable.exe
    

You will now have a new executable with all your libraries in one!

How to set iPhone UIView z index?

If you want to do this through XCode's Interface Builder, you can use the menu options under Editor->Arrangement. There you'll find "Send to Front", "Send to Back", etc.

Python safe method to get value of nested dictionary

For nested dictionary/JSON lookups, you can use dictor

pip install dictor

dict object

{
    "characters": {
        "Lonestar": {
            "id": 55923,
            "role": "renegade",
            "items": [
                "space winnebago",
                "leather jacket"
            ]
        },
        "Barfolomew": {
            "id": 55924,
            "role": "mawg",
            "items": [
                "peanut butter jar",
                "waggy tail"
            ]
        },
        "Dark Helmet": {
            "id": 99999,
            "role": "Good is dumb",
            "items": [
                "Shwartz",
                "helmet"
            ]
        },
        "Skroob": {
            "id": 12345,
            "role": "Spaceballs CEO",
            "items": [
                "luggage"
            ]
        }
    }
}

to get Lonestar's items, simply provide a dot-separated path, ie

import json
from dictor import dictor

with open('test.json') as data: 
    data = json.load(data)

print dictor(data, 'characters.Lonestar.items')

>> [u'space winnebago', u'leather jacket']

you can provide fallback value in case the key isnt in path

theres tons more options you can do, like ignore letter casing and using other characters besides '.' as a path separator,

https://github.com/perfecto25/dictor

Illegal pattern character 'T' when parsing a date string to java.util.Date

tl;dr

Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

Instant.parse( "2010-10-02T12:23:23Z" )

ISO 8601

That format is defined by the ISO 8601 standard for date-time string formats.

Both:

…use ISO 8601 formats by default for parsing and generating strings.

You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

java.time

Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.

Convert to the old class.

java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.

Time Zone

If needed, you can assign a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.

Convert.

java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Here is some example code in Joda-Time 2.8.

org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.

Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.

Time Zone

If needed, you can assign a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ImportError: No module named matplotlib.pyplot

Comment in the normal feed are blocked. Let me write why this happens, just like when you executed your app.

If you ran scripts, python or ipython in another environment than the one you installed it, you will get these issues.

Don't confuse reinstalling it. Matplotlib is normally installed in your user environment, not in sudo. You are changing the environment.

So don't reinstall pip, just make sure you are running it as sudo if you installed it in the sudo environment.

Phone Number Validation MVC

To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.

Usage

@Html.DisplayForPhone(item.Phone)

HtmlHelper Extension

public static class HtmlHelperExtensions
{
    public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
    {
        if (phone == null)
        {
            return new HtmlString(string.Empty);
        }
        string formatted = phone;
        if (phone.Length == 10)
        {
            formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
        }
        else if (phone.Length == 7)
        {
            formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
        }
        string s = $"<a href='tel:{phone}'>{formatted}</a>";
        return new HtmlString(s);
    }
}

What is the difference between Scala's case class and class?

  • Case classes define a compagnon object with apply and unapply methods
  • Case classes extends Serializable
  • Case classes define equals hashCode and copy methods
  • All attributes of the constructor are val (syntactic sugar)

How can I get column names from a table in SQL Server?

One other option which is arguably more intuitive is:

SELECT [name] 
FROM sys.columns 
WHERE object_id = OBJECT_ID('[yourSchemaType].[yourTableName]') 

This gives you all your column names in a single column. If you care about other metadata, you can change edit the SELECT STATEMENT TO SELECT *.

How to read data from java properties file using Spring Boot

i would suggest the following way:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

Difference between two dates in MySQL

This code calculate difference between two dates in yyyy MM dd format.

declare @StartDate datetime 
declare @EndDate datetime

declare @years int
declare @months int 
declare @days int

--NOTE: date of birth must be smaller than As on date, 
--else it could produce wrong results
set @StartDate = '2013-12-30' --birthdate
set @EndDate  = Getdate()            --current datetime

--calculate years
select @years = datediff(year,@StartDate,@EndDate)

--calculate months if it's value is negative then it 
--indicates after __ months; __ years will be complete
--To resolve this, we have taken a flag @MonthOverflow...
declare @monthOverflow int
select @monthOverflow = case when datediff(month,@StartDate,@EndDate) - 
  ( datediff(year,@StartDate,@EndDate) * 12) <0 then -1 else 1 end
--decrease year by 1 if months are Overflowed
select @Years = case when @monthOverflow < 0 then @years-1 else @years end
select @months =  datediff(month,@StartDate,@EndDate) - (@years * 12) 

--as we do for month overflow criteria for days and hours 
--& minutes logic will followed same way
declare @LastdayOfMonth int
select @LastdayOfMonth =  datepart(d,DATEADD
    (s,-1,DATEADD(mm, DATEDIFF(m,0,@EndDate)+1,0)))

select @days = case when @monthOverflow<0 and 
    DAY(@StartDate)> DAY(@EndDate) 
then @LastdayOfMonth + 
  (datepart(d,@EndDate) - datepart(d,@StartDate) ) - 1  
      else datepart(d,@EndDate) - datepart(d,@StartDate) end 


select
 @Months=case when @days < 0 or DAY(@StartDate)> DAY(@EndDate) then @Months-1 else @Months end

Declare @lastdayAsOnDate int;
set @lastdayAsOnDate = datepart(d,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@EndDate),0)));
Declare @lastdayBirthdate int;
set @lastdayBirthdate =  datepart(d,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@StartDate)+1,0)));

if (@Days < 0) 
(
    select @Days = case when( @lastdayBirthdate > @lastdayAsOnDate) then
        @lastdayBirthdate + @Days
    else
        @lastdayAsOnDate + @Days
    end
)
print  convert(varchar,@years)   + ' year(s),   '  +
       convert(varchar,@months)  + ' month(s),   ' +
       convert(varchar,@days)    + ' day(s)   '   

Reading int values from SqlDataReader

This should work:

txtfarmersize = Convert.ToInt32(reader["farmsize"]);

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

Docker Compose wait for container X before starting Y

Finally found a solution with a docker-compose method. Since docker-compose file format 2.1 you can define healthchecks.

I did it in a example project you need to install at least docker 1.12.0+. I also needed to extend the rabbitmq-management Dockerfile, because curl isn't installed on the official image.

Now I test if the management page of the rabbitmq-container is available. If curl finishes with exitcode 0 the container app (python pika) will be started and publish a message to hello queue. Its now working (output).

docker-compose (version 2.1):

version: '2.1'

services:
  app:
    build: app/.
    depends_on:
      rabbit:
        condition: service_healthy
    links: 
        - rabbit

  rabbit:
    build: rabbitmq/.
    ports: 
        - "15672:15672"
        - "5672:5672"
    healthcheck:
        test: ["CMD", "curl", "-f", "http://localhost:15672"]
        interval: 30s
        timeout: 10s
        retries: 5

output:

rabbit_1  | =INFO REPORT==== 25-Jan-2017::14:44:21 ===
rabbit_1  | closing AMQP connection <0.718.0> (172.18.0.3:36590 -> 172.18.0.2:5672)
app_1     |  [x] Sent 'Hello World!'
healthcheckcompose_app_1 exited with code 0

Dockerfile (rabbitmq + curl):

FROM rabbitmq:3-management
RUN apt-get update
RUN apt-get install -y curl 
EXPOSE 4369 5671 5672 25672 15671 15672

Version 3 no longer supports the condition form of depends_on. So i moved from depends_on to restart on-failure. Now my app container will restart 2-3 times until it is working, but it is still a docker-compose feature without overwriting the entrypoint.

docker-compose (version 3):

version: "3"

services:

  rabbitmq: # login guest:guest
    image: rabbitmq:management
    ports:
    - "4369:4369"
    - "5671:5671"
    - "5672:5672"
    - "25672:25672"
    - "15671:15671"
    - "15672:15672"
    healthcheck:
        test: ["CMD", "curl", "-f", "http://localhost:15672"]
        interval: 30s
        timeout: 10s
        retries: 5

  app:
    build: ./app/
    environment:
      - HOSTNAMERABBIT=rabbitmq
    restart: on-failure
    depends_on:
      - rabbitmq
    links: 
        - rabbitmq

Java: get greatest common divisor

Is it somewhere else?

Apache! - it has both gcd and lcm, so cool!

However, due to profoundness of their implementation, it's slower compared to simple hand-written version (if it matters).

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Bootstrap alert in a fixed floating div at the top of page

You can use this class : class="sticky-top alert alert-dismissible"

How to set default value for HTML select?

You should define the attributes of option like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

Git Diff with Beyond Compare

The Beyond Compare support page is a bit brief.

Check my diff.external answer for more (regarding the exact syntax)

Extract:

$ git config --global diff.external <path_to_wrapper_script>

at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains

-->8-(snip)--
[diff]
    external = <path_to_wrapper_script>
--8<-(snap)--

Be sure to use the correct syntax to specify the paths to the wrapper script and diff tool, i.e. use forward slashed instead of backslashes. In my case, I have

[diff]
    external = c:/Documents and Settings/sschuber/git-diff-wrapper.sh

in .gitconfig and

"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat

in the wrapper script.


Note: you can also use git difftool.

When to use IMG vs. CSS background-image?

HTML is for content and CSS is for design. Is the image necessary and does it need to be picked up by screen readers? If the answer is yes, then put the image in the HTML. If it is purely for styling, then you can use the background-image property in CSS to inject the image. Just as a lot of people here have already mentioned, you can then use a pseudo element on the image if you like.

Proper usage of .net MVC Html.CheckBoxFor

Place this on your model:

[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }

private string electricFanRate;

public string ElectricFanRate
{
    get { return electricFanRate ?? (electricFanRate = "$15/month"); }
    set { electricFanRate = value; }
}

And this in your cshtml:

<div class="row">
    @Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
    @Html.LabelFor(m => m.ElectricFan, new { @class = "" })
    @Html.DisplayTextFor(m => m.ElectricFanRate)
</div>

Which will output this:

MVC Output If you click on the checkbox or the bold label it will check/uncheck the checkbox

Difference between spring @Controller and @RestController annotation

@RestController is the combination of @Controller and @ResponseBody.

Flow of request in a @Controller class without using a @ResponseBody annotation:

enter image description here

@RestController returns an object as response instead of view.

enter image description here

Date difference in years using C#

Here is a neat trick which lets the system deal with leap years automagically. It gives an accurate answer for all date combinations.

DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0);
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0);

DateTime tmp = dt1;
int years = -1;
while (tmp < dt2)
{
    years++;
    tmp = tmp.AddYears(1);
}

Console.WriteLine("{0}", years);

Difference between application/x-javascript and text/javascript content types

According to RFC 4329 the correct MIME type for JavaScript should be application/javascript. Howerver, older IE versions choke on this since they expect text/javascript.

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

You may need to add a JDK (Java Development Kit) to the installed JRE's within Eclipse

Go to Window->Preferences->Java->Installed JRE's

In the Name column if you do not have a JDK as your default, then you will need to add it.

Click the "Add" Button and locate the JDK on your machine. You may find it in this location: C:\Program Files\Java\jdk1.x.y
Where x and y are numbers.

If there are no JDK's installed on your machine then download and install the Java SE (Standard Edition) from the Oracle website.

Then do the steps above again. Be sure that it is set as the default JRE to use.

Then go back to the Projects->Generate Javadoc... dialog

Now it should work.

Good Luck.

Using jQuery how to get click coordinates on the target element

Try this:

jQuery(document).ready(function(){
   $("#special").click(function(e){
      $('#status2').html(e.pageX +', '+ e.pageY);
   }); 
})

Here you can find more info with DEMO

How to reference a file for variables using Bash?

The script containing variables can be executed imported using bash. Consider the script-variable.sh

#!/bin/sh
scr-var=value

Consider the actual script where the variable will be used :

 #!/bin/sh
 bash path/to/script-variable.sh
 echo "$scr-var"

How to find the size of an int[]?

This method work when you are using a class: In this example you will receive a array, so the only method that worked for me was these one:

template <typename T, size_t n, size_t m>   
Matrix& operator= (T (&a)[n][m])
{   

    int arows = n;
    int acols = m;

    p = new double*[arows];

    for (register int r = 0; r < arows; r++)
    {
        p[r] = new double[acols];


        for (register int c = 0; c < acols; c++)
        {
            p[r][c] = a[r][c]; //A[rows][columns]
        }

}

https://www.geeksforgeeks.org/how-to-print-size-of-an-array-in-a-function-in-c/

Entity Framework and SQL Server View

Due to the above mentioned problems, I prefer table value functions.

If you have this:

CREATE VIEW [dbo].[MyView] AS SELECT A, B FROM dbo.Something

create this:

CREATE FUNCTION MyFunction() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[MyView])

Then you simply import the function rather than the view.

How do I set the time zone of MySQL?

You can specify the server's default timezone when you start it, see http://dev.mysql.com/doc/refman/5.1/en/server-options.html and specifically the --default-time-zone=timezone option. You can check the global and session time zones with

SELECT @@global.time_zone, @@session.time_zone;

set either or both with the SET statement, &c; see http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html for many more details.

How to display 3 buttons on the same line in css

Do something like this,

HTML :

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div>

CSS :

div button{
    display:inline-block;
}

Fiddle Demo

Or

HTML :

<div style="width:500px;" id="container">
    <div><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
    <div><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
    <div><button class="msgBtnBack">Back</button></div>
</div>

CSS :

#container div{
    display:inline-block;
    width:130px;
}

Fiddle Demo

Syntax for a single-line Bash infinite while loop

It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done

Copy array items into another array

If you want to modify the original array, you can spread and push:

var source = [1, 2, 3];
var range = [5, 6, 7];
var length = source.push(...range);

console.log(source); // [ 1, 2, 3, 5, 6, 7 ]
console.log(length); // 6

If you want to make sure only items of the same type go in the source array (not mixing numbers and strings for example), then use TypeScript.

/**
 * Adds the items of the specified range array to the end of the source array.
 * Use this function to make sure only items of the same type go in the source array.
 */
function addRange<T>(source: T[], range: T[]) {
    source.push(...range);
}

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Try this, it will combine your arrays removing duplicates

array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]

array3 = array1|array2

http://www.ruby-doc.org/core/classes/Array.html

Further documentation look at "Set Union"

Get hours difference between two dates in Moment Js

 var start=moment(1541243900000);
 var end=moment(1541243942882);
 var duration = moment.duration(end.diff(startTime));
 var hours = duration.asHours();

As you can see, the start and end date needed to be moment objects for this method to work.

Paging with LINQ for objects

    public LightDataTable PagerSelection(int pageNumber, int setsPerPage, Func<LightDataRow, bool> prection = null)
    {
        this.setsPerPage = setsPerPage;
        this.pageNumber = pageNumber > 0 ? pageNumber - 1 : pageNumber;
        if (!ValidatePagerByPageNumber(pageNumber))
            return this;

        var rowList = rows.Cast<LightDataRow>();
        if (prection != null)
            rowList = rows.Where(prection).ToList();

        if (!rowList.Any())
            return new LightDataTable() { TablePrimaryKey = this.tablePrimaryKey };
        //if (rowList.Count() < (pageNumber * setsPerPage))
        //    return new LightDataTable(new LightDataRowCollection(rowList)) { TablePrimaryKey = this.tablePrimaryKey };

        return new LightDataTable(new LightDataRowCollection(rowList.Skip(this.pageNumber * setsPerPage).Take(setsPerPage).ToList())) { TablePrimaryKey = this.tablePrimaryKey };
  }

this is what i did. Normaly you start at 1 but in IList you start with 0. so if you have 152 rows that mean you have 8 paging but in IList you only have 7. hop this can make thing clear for you

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

For me, I missed this statement in @Component decorator: animations: [yourAnimation]

Once I added this statement, errors gone. (Angular 6.x)

Using isKindOfClass with Swift

Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How to fill color in a cell in VBA?

  1. Select all cells by left-top corner
  2. Choose [Home] >> [Conditional Formatting] >> [New Rule]
  3. Choose [Format only cells that contain]
  4. In [Format only cells with:], choose "Errors"
  5. Choose proper formats in [Format..] button

Showing all session data at once?

print_r($this->session->userdata); 

or

print_r($this->session->all_userdata());

How to remove all namespaces from XML with C#?

This is a solution based on Peter Stegnar's accepted answer.

I used it, but (as andygjp and John Saunders remarked) his code ignores attributes.

I needed to take care of attributes too, so I adapted his code. Andy's version was Visual Basic, this is still c#.

I know it's been a while, but perhaps it'll save somebody some time one day.

    private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        XElement xmlDocumentWithoutNs = removeAllNamespaces(xmlDocument);
        return xmlDocumentWithoutNs;
    }

    private static XElement removeAllNamespaces(XElement xmlDocument)
    {
        var stripped = new XElement(xmlDocument.Name.LocalName);            
        foreach (var attribute in
                xmlDocument.Attributes().Where(
                attribute =>
                    !attribute.IsNamespaceDeclaration &&
                    String.IsNullOrEmpty(attribute.Name.NamespaceName)))
        {
            stripped.Add(new XAttribute(attribute.Name.LocalName, attribute.Value));
        }
        if (!xmlDocument.HasElements)
        {
            stripped.Value = xmlDocument.Value;
            return stripped;
        }
        stripped.Add(xmlDocument.Elements().Select(
            el =>
                RemoveAllNamespaces(el)));            
        return stripped;
    }

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Problem: Even I was facing the problem where we were sending '£' with some string in POST request to CRM System, but when we were doing the GET call from CRM , it was returning '£' with some string content. So what we have analysed is that '£' was getting converted to '£'.

Analysis: The glitch which we have found after doing research is that in POST call we have set HttpWebRequest ContentType as "text/xml" while in GET Call it was "text/xml; charset:utf-8".

Solution: So as the part of solution we have included the charset:utf-8 in POST request and it works.

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

Incorrect syntax near ''

I was using ADO.NET and was using SQL Command as:

 string query =
"SELECT * " +
"FROM table_name" +
"Where id=@id";

the thing was i missed a whitespace at the end of "FROM table_name"+ So basically it said

string query = "SELECT * FROM table_nameWHERE id=@id";

and this was causing the error.

Hope it helps

QED symbol in latex

The question specifically mentions a full box and not an empty box and not using proof environment from amsthm package. Hence, an option may be to use the command \QED from the package stix. It reproduces the character U+220E (end of proof, ?).

How to execute an .SQL script file using c#

Added additional improvements to surajits answer:

using System;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;

namespace MyNamespace
{
    public partial class RunSqlScript : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var connectionString = @"your-connection-string";
            var pathToScriptFile = Server.MapPath("~/sql-scripts/") + "sql-script.sql";
            var sqlScript = File.ReadAllText(pathToScriptFile);

            using (var connection = new SqlConnection(connectionString))
            {
                var server = new Server(new ServerConnection(connection));
                server.ConnectionContext.ExecuteNonQuery(sqlScript);
            }
        }
    }
}

Also, I had to add the following references to my project:

  • C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
  • C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll

I have no idea if those are the right dll:s to use since there are several folders in C:\Program Files\Microsoft SQL Server but in my application these two work.

Twitter Bootstrap: Print content of modal window

I would suggest you try this jQuery plugin print element

It can let you just print the element you selected.

C# equivalent to Java's charAt()?

you can use LINQ

string abc = "abc";
char getresult = abc.Where((item, index) => index == 2).Single();

How to print environment variables to the console in PowerShell?

The following is works best in my opinion:

Get-Item Env:PATH
  1. It's shorter and therefore a little bit easier to remember than Get-ChildItem. There's no hierarchy with environment variables.
  2. The command is symmetrical to one of the ways that's used for setting environment variables with Powershell. (EX: Set-Item -Path env:SomeVariable -Value "Some Value")
  3. If you get in the habit of doing it this way you'll remember how to list all Environment variables; simply omit the entry portion. (EX: Get-Item Env:)

I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.

What's the point of the trailing colon in Env:? Try listing all of the "drives" available through Providers like this:

PS> Get-PSDrive

I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.

You can navigate the drives and pick out specific values:

Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM

What is the difference between & and && in Java?

& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

String date to xmlgregoriancalendar conversion

tl;dr

  • Use modern java.time classes as much as possible, rather than the terrible legacy classes.
  • Always specify your desired/expected time zone or offset-from-UTC rather than rely implicitly on JVM’s current default.

Example code (without exception-handling):

XMLGregorianCalendar xgc = 
    DatatypeFactory                           // Data-type converter.
    .newInstance()                            // Instantiate a converter object.
    .newXMLGregorianCalendar(                 // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
        GregorianCalendar.from(               // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
            LocalDate                         // Modern class for representing a date-only, without time-of-day and without time zone.
            .parse( "2014-01-07" )            // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern. 
            .atStartOfDay( ZoneOffset.UTC )   // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
        )                                     // Returns a `GregorianCalendar` object.
    )                                         // Returns a `XMLGregorianCalendar` object.
;

Parsing date-only input string into an object of XMLGregorianCalendar class

Avoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar, GregorianCalendar, Calendar, and Date. Use only modern java.time classes.

When presented with a string such as "2014-01-07", parse as a LocalDate.

LocalDate.parse( "2014-01-07" )

To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.

LocalDate.parse( "2014-01-07" )
         .atStartOfDay( ZoneId.of( "America/Montreal" ) )

This returns a ZonedDateTime object.

ZonedDateTime zdt = 
        LocalDate
        .parse( "2014-01-07" )
        .atStartOfDay( ZoneId.of( "America/Montreal" ) )
;

zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]

But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC constant as our ZoneId argument.

ZonedDateTime zdt = 
        LocalDate
        .parse( "2014-01-07" )
        .atStartOfDay( ZoneOffset.UTC )
;

zdt.toString() = 2014-01-07T00:00Z

The Z on the end means UTC (an offset of zero), and is pronounced “Zulu”.

If you must work with legacy classes, convert to GregorianCalendar, a subclass of Calendar.

GregorianCalendar gc = GregorianCalendar.from( zdt ) ;

gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]

Apparently, you really need an object of the legacy class XMLGregorianCalendar. If the calling code cannot be updated to use java.time, convert.

XMLGregorianCalendar xgc = 
        DatatypeFactory
        .newInstance()
        .newXMLGregorianCalendar( gc ) 
;

Actually, that code requires a try-catch.

try
{
    XMLGregorianCalendar xgc =
            DatatypeFactory
                    .newInstance()
                    .newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
    e.printStackTrace();
}

xgc = 2014-01-07T00:00:00.000Z

Putting that all together, with appropriate exception-handling.

// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC. 
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
    Objects.requireNonNull( input );
    if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
    XMLGregorianCalendar xgc = null;
    ZonedDateTime zdt = null;

    try
    {
        zdt =
                LocalDate
                        .parse( input )
                        .atStartOfDay( ZoneOffset.UTC );
    }
    catch ( DateTimeParseException e )
    {
        throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
    }

    GregorianCalendar gc = GregorianCalendar.from( zdt );
    try
    {
        xgc =
                DatatypeFactory
                        .newInstance()
                        .newXMLGregorianCalendar( gc );
    }
    catch ( DatatypeConfigurationException e )
    {
        e.printStackTrace();
    }

    Objects.requireNonNull( xgc );
    return xgc ;
}

Usage.

String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );

Dump to console.

System.out.println( "xgc = " + xgc );

xgc = 2014-01-07T00:00:00.000Z

Modern date-time classes versus legacy

Table of date-time types in Java, both modern and legacy

Date-time != String

Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.

So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.

Avoid legacy date-time classes

The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.

ISO 8601

Your input string "2014-01-07" is in standard ISO 8601 format.

The T in the middle separates date portion from time portion.

The Z on the end is short for Zulu and means UTC.

Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2014-01-07" ) ;

ld.toString(): 2014-01-07

Start of day ZonedDateTime

If you want to see the first moment of that day, specify a ZoneId time zone to get a moment on the timeline, a ZonedDateTime. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;

zdt.toString(): 2014-01-07T00:00:00Z

For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME and then replace the T in the middle with a SPACE.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " ) ; 

2014-01-07 00:00:00


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

HTML5 - mp4 video does not play in IE9

Internet Explorer and Edge do not support some MP4 formats that Chrome does. You can use ffprobe to see the exact MP4 format. In my case I have these two videos:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf56.40.101
  Duration: 00:00:12.10, start: 0.000000, bitrate: 287 kb/s
    Stream #0:0(und): Video: h264 (High 4:4:4 Predictive) (avc1 / 0x31637661), yuv444p, 1000x1000 [SAR 1:1 DAR 1:1], 281 kb/s, 60 fps, 60 tbr, 15360 tbn, 120 tbc (default)
    Metadata:
      handler_name    : VideoHandler


Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'b.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.66.102
  Duration: 00:00:33.83, start: 0.000000, bitrate: 505 kb/s
    Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 1280x680, 504 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
    Metadata:
      handler_name    : VideoHandler

Both play fine in Chrome, but the first one fails in IE and Edge. The problem is that IE and Edge don't support yuv444. You can convert to a shittier colourspace like this:

ffmpeg -i input.mp4 -pix_fmt yuv420p output.mp4

How to import a bak file into SQL Server Express

Restoring a Database from Backup

sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
            DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK

jQuery animate scroll

I just use:

_x000D_
_x000D_
$('body').animate({ 'scrollTop': '-=-'+<yourValueScroll>+'px' }, 2000);
_x000D_
_x000D_
_x000D_

How to display a date as iso 8601 format with PHP

Using the DateTime class available in PHP version 5.2 it would be done like this:

$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');

See it in action

As of PHP 5.4 you can do this as a one-liner:

echo (new DateTime('17 Oct 2008'))->format('c');

How are Anonymous inner classes used in Java?

They're commonly used as a verbose form of callback.

I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)

Here's a swing example

myButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do stuff here...
    }
});

Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

PostgreSQL - max number of parameters in "IN" clause?

explain select * from test where id in (values (1), (2));

QUERY PLAN

 Seq Scan on test  (cost=0.00..1.38 rows=2 width=208)
   Filter: (id = ANY ('{1,2}'::bigint[]))

But if try 2nd query:

explain select * from test where id = any (values (1), (2));

QUERY PLAN

Hash Semi Join  (cost=0.05..1.45 rows=2 width=208)
       Hash Cond: (test.id = "*VALUES*".column1)
       ->  Seq Scan on test  (cost=0.00..1.30 rows=30 width=208)
       ->  Hash  (cost=0.03..0.03 rows=2 width=4)
             ->  Values Scan on "*VALUES*"  (cost=0.00..0.03 rows=2 width=4)

We can see that postgres build temp table and join with it

JSHint and jQuery: '$' is not defined

Here is a happy little list to put in your .jshintrc
I will add to this list at time passes.

{
  // other settings...
  // ENVIRONMENTS
  // "browser": true, // Is in most configs by default
  "node": true,
  // others (e.g. yui, mootools, rhino, worker, etc.)
  "globals": {
    "$":false,
    "jquery":false,
    "angular":false
    // other explicit global names to exclude
  },
}

Gitignore not working

After going down a bit of a bit of a rabbit hole trying to follow the answers to this question (maybe because I had to do this in a visual studio project), I found the easier path was to

  1. Cut and paste the file(s) I no longer want to track into a temporary location

  2. Commit the "deletion" of those files

  3. Commit a modification of the .gitignore to exclude the files I had temporarily moved

  4. Move the files back into the folder.

I found this to be the most straight forward way to go about it (at least in a visual studio, or I would assume other IDE heave based environment like Android Studio), without accidentally shooting myself in the foot with a pretty pervasive git rm -rf --cached . , after which the visual studio project I was working on didn't load.

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

Base table or view not found: 1146 Table Laravel 5

I'm guessing Laravel can't determine the plural form of the word you used for your table name.

Just specify your table in the model as such:

class Cotizacion extends Model{
    public $table = "cotizacion";

How to adjust an UIButton's imageSize?

Heres the Swift version:

myButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

How can I get a list of Git branches, ordered by most recent commit?

Here's the variation I was looking for:

git for-each-ref --sort=-committerdate --format='%(committerdate)%09%(refname:short)' refs/heads/ | tail -r

That tail -r reverses the list so the most-recent commiterdate is last.

Android global variable

If possible, you should declare the variables that you need to keep alive that haven't been clear by Garbage Collector or Unload by OS in file .so To do it, you must code by C/C++ and compile to .so lib file and load it in your MainActivity.

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Your use with boost::mutex is exactly what this keyword is intended for. Another use is for internal result caching to speed access.

Basically, 'mutable' applies to any class attribute that does not affect the externally visible state of the object.

In the sample code in your question, mutable might be inappropriate if the value of done_ affects external state, it depends on what is in the ...; part.

Where can I find php.ini?

This works for me:

php -i | grep 'php.ini'

You should see something like:

Loaded Configuration File => /usr/local/lib/php.ini

p.s. To get only the php.inin path

php -i | grep /.+/php.ini -oE

How to checkout a specific Subversion revision from the command line?

You'll have to use svn directly:

svn checkout URL[@REV]... [PATH]

and

svn help co

gives you a little more help.

How to extract numbers from a string in Python?

Since none of these dealt with real world financial numbers in excel and word docs that I needed to find, here is my variation. It handles ints, floats, negative numbers, currency numbers (because it doesn't reply on split), and has the option to drop the decimal part and just return ints, or return everything.

It also handles Indian Laks number system where commas appear irregularly, not every 3 numbers apart.

It does not handle scientific notation or negative numbers put inside parentheses in budgets -- will appear positive.

It also does not extract dates. There are better ways for finding dates in strings.

import re
def find_numbers(string, ints=True):            
    numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
    numbers = numexp.findall(string)    
    numbers = [x.replace(',','') for x in numbers]
    if ints is True:
        return [int(x.replace(',','').split('.')[0]) for x in numbers]            
    else:
        return numbers

Convert/cast an stdClass object to another class

See the manual on Type Juggling on possible casts.

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.

Or, if you are in a hackish mood, you could adapt the following code:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(serialize($array), ':')
    ));
}

which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.

For object to object, the code would be

function objectToObject($instance, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(strstr(serialize($instance), '"'), ':')
    ));
}

How to create a directory in Java?

The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()

private void createUserDir(final String dirName) throws IOException {
    final File homeDir = new File(System.getProperty("user.home"));
    final File dir = new File(homeDir, dirName);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Unable to create " + dir.getAbsolutePath();
    }
}

How to get the current user in ASP.NET MVC

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData, or you could just call User as I think it's a property of ViewPage.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

How to set image to fit width of the page using jsPDF?

I discovered this while experimenting with html2canvas this morning. While this doesn't include provisions for printing multiple pages it does scale the image to page width and reframes the height in ratio to the adjusted width:

html2canvas(document.getElementById('testdiv')).then(function(canvas){
        var wid: number
        var hgt: number
        var img = canvas.toDataURL("image/png", wid = canvas.width, hgt = canvas.height);
        var hratio = hgt/wid
        var doc = new jsPDF('p','pt','a4');
        var width = doc.internal.pageSize.width;    
        var height = width * hratio
        doc.addImage(img,'JPEG',20,20, width, height);
        doc.save('Test.pdf');
    });

When 1 px border is added to div, Div size increases, Don't want to do that

I needed to be able to "border" any element by adding a class and not affect its dimensions. A good solution for me was to use box-shadow. But in some cases the effect was not visible due to other siblings. So I combined both typical box-shadow as well as inset box-shadow. The result is a border look without changing any dimensions.

Values separated by comma. Here's a simple example:

.add_border {
    box-shadow:-1px 0 1px 1px rgba(0, 0, 0, 0.75), inset -1px 0 0 1px rgba(0, 0, 0, 0.75);
}

jsfiddle

Adjust for your preferred look and you're good to go!

CSS class for pointer cursor

You can assign "button" to role attribute of any html tag/element to make pointer over it. i.e

<html-element role="button" />

How can I parse a local JSON file from assets folder into a ListView?

With Kotlin have this extension function to read the file return as string.

fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

Parse the output string using any JSON parser.

Image size (Python, OpenCV)

from this tutorial: https://www.tutorialkart.com/opencv/python/opencv-python-get-image-size/

import cv2

# read image
img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED)

# get dimensions of image
dimensions = img.shape

# height, width, number of channels in image

height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]

from this other tutorial: https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/

image = cv2.imread("jp.png")

(h, w, d) = image.shape

Please double check things before posting answers.

node.js: read a text file into an array. (Each line an item in the array.)

file.lines with JFile package

Pseudo

var JFile=require('jfile');

var myF=new JFile("./data.txt");
myF.lines // ["first line","second line"] ....

Don't forget before :

npm install jfile --save

How to uninstall a Windows Service when there is no executable for it left on the system?

Create a copy of executables of same service and paste it on the same path of the existing service and then uninstall.

Can an AWS Lambda function call another

here's a sample code for python,

from boto3 import client as boto3_client
from datetime import datetime
import json

lambda_client = boto3_client('lambda')

def lambda_handler(event, context):
    msg = {"key":"new_invocation", "at": datetime.now()}
    invoke_response = lambda_client.invoke(FunctionName="another_lambda_",
                                           InvocationType='Event',
                                           Payload=json.dumps(msg))
    print(invoke_response)

Btw, you would need to add a policy like this to your lambda role as well

   {
        "Sid": "Stmt1234567890",
        "Effect": "Allow",
        "Action": [
            "lambda:InvokeFunction"
        ],
        "Resource": "*"
    }

How to clear browser cache with php?

You can delete the browser cache by setting these headers:

<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

This could be due to the service endpoint binding not using the HTTP protocol

Also had this issue and it was due to forgetting to decorate my model with DataContract and DataMember attributes

how to set select element as readonly ('disabled' doesnt pass select value on server)

You can simulate a readonly select box using the CSS pointer-events property:

select[readonly]
{
    pointer-events: none;
}

The HTML tabindex property will also prevent it from being selected by keyboard tabbing:

<select tabindex="-1">

_x000D_
_x000D_
select[readonly]_x000D_
{_x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
  background: #fafafa;_x000D_
  border: 1px solid #ccc;_x000D_
  color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
  display:block;_x000D_
  width: 20rem;_x000D_
  padding: 0.5rem;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
  <input type="text" value="this is a normal text box">_x000D_
  <input type="text" readonly value="this is a readonly text box">_x000D_
  <select readonly tabindex="-1">_x000D_
    <option>This is a readonly select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
  <select>_x000D_
    <option>This is a normal select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).

        <!-- Note: set the initial collapsed state and change it when clicking -->
        <a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
        </a>
        <a class="brand" href="#">Title</a>
           <!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
           <div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
              <ul class="nav">

That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.


Release 0.14 added a uib- prefix to components:

https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes

Change: collapse to uib-collapse.

How can I know if Object is String type object?

Could you not use typeof(object) to compare against

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You could make a recursive function do the work

  • Let L = size(M)
  • Let idx = zeros(L,1)
  • Take length(L) as the maximum depth
  • Loop for idx(depth) = 1:L(depth)
  • If your depth is length(L), do the element operation, else call the function again with depth+1

Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.

Capitalize words in string

I would use regex for this purpose:

myString = '  this Is my sTring.  ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));

Remove border radius from Select tag in bootstrap 3

In addition to border-radius: 0, add -webkit-appearance: none;.

Android Studio Stuck at Gradle Download on create new project

For Windows Users

Use your Network Resource Monitor

enter image description here

Open Task Manager [Ctrl+Shift+Esc]

Performance Tab

Open Resource Monitor (From the bottom)

First i decided to wait after reading answers here. But how long..? How to make sure it will finish.? They should have provided percentage of download, but they have not. So to know some kind of progress is going on, open this network resource monitor, it will show you some kind of download is going on for the Studio64.exe. IF not (if it shows 0B/Sec), then either network is not available or the application is not responding.

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Highlighting Text Color using Html.fromHtml() in Android?

 String name = modelOrderList.get(position).getName();   //get name from List
    String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
    /* check API version, according to version call method of Html class  */
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
        Log.d(TAG, "onBindViewHolder: if");
        holder.textViewName.setText(context.getString(R.string._5687982) + " ");
        holder.textViewName.append(Html.fromHtml(text));
    } else {
        Log.d(TAG, "onBindViewHolder: else");
        holder.textViewName.setText("123456" + " ");   //set text 
        holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));   //append text into textView
    }

Can an XSLT insert the current date?

Late answer, but my solution works in Eclipse XSLT. Eclipse uses XSLT 1 at time of this writing. You can install an XSLT 2 engine like Saxon. Or you can use the XSLT 1 solution below to insert current date and time.

<xsl:value-of select="java:util.Date.new()"/>

This will call Java's Data class to output the date. It will not work unless you also put the following "java:" definition in your <xsl:stylesheet> tag.

<xsl:stylesheet [...snip...]
         xmlns:java="java"
         [...snip...]>

I hope that helps someone. This simple answer was difficult to find for me.

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How can I get the current class of a div with jQuery?

The addClass method in jQuery has a currentClass built in property. You can use it inside a function call. Like so:

<div>First div</div>
<div class="red">Second div</div>
<div>Third div</div>
<div>Fourth div</div>

<script>
  $("div").addClass(function(index, currentClass) {
    var addedClass;
    if ( currentClass === "red" ) {
      addedClass = "green"; }
    return addedClass;
  });
</script>

how do I give a div a responsive height

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.

If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.

However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.

My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.

Execution failed for task ':app:compileDebugAidl': aidl is missing

It has been fixed two days ago, so you can use:

buildToolsVersion '23.0.0 rc2'

with the newest android gradle plugin:

classpath 'com.android.tools.build:gradle:1.3.0-beta2'

Note: I had some weird problems with gradle 2.4 distribution, but trying to build the project again has fixed that for me.

EDIT

There is a newer version of build-tools 23, so you should probably use:

buildToolsVersion '23.0.0 rc3'

EDIT 2

And yet again, there are newer version of both gradle plugin and build-tools, so you can switch to using:

classpath 'com.android.tools.build:gradle:1.3.0'

and

buildToolsVersion '23.0.0'

How to convert a byte to its binary string representation

Use Integer#toBinaryString():

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010

DEMO.

Hide all warnings in ipython

I eventually figured it out. Place:

import warnings
warnings.filterwarnings('ignore')

inside ~/.ipython/profile_default/startup/disable-warnings.py. I'm leaving this question and answer for the record in case anyone else comes across the same issue.

Quite often it is useful to see a warning once. This can be set by:

warnings.filterwarnings(action='once')

What is Type-safe?

An explanation from a liberal arts major, not a comp sci major:

When people say that a language or language feature is type safe, they mean that the language will help prevent you from, for example, passing something that isn't an integer to some logic that expects an integer.

For example, in C#, I define a function as:

 void foo(int arg)

The compiler will then stop me from doing this:

  // call foo
  foo("hello world")

In other languages, the compiler would not stop me (or there is no compiler...), so the string would be passed to the logic and then probably something bad will happen.

Type safe languages try to catch more at "compile time".

On the down side, with type safe languages, when you have a string like "123" and you want to operate on it like an int, you have to write more code to convert the string to an int, or when you have an int like 123 and want to use it in a message like, "The answer is 123", you have to write more code to convert/cast it to a string.

Extracting substrings in Go

It looks like you're confused by the working of slices and the string storage format, which is different from what you have in C.

  • any slice in Go stores the length (in bytes), so you don't have to care about the cost of the len operation : there is no need to count
  • Go strings aren't null terminated, so you don't have to remove a null byte, and you don't have to add 1 after slicing by adding an empty string.

To remove the last char (if it's a one byte char), simply do

inputFmt:=input[:len(input)-1]

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

I had the error when using gpg-agent as my ssh-agent and using a gpg subkey as my ssh key https://wiki.archlinux.org/index.php/GnuPG#gpg-agent.

I suspect that the problem was caused by having an invalid pin entry tty for gpg caused by my sleep+lock command used in my sway config

bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock'"

or just the sleep/suspend

Reset the pin entry tty to fix the problem

gpg-connect-agent updatestartuptty /bye > /dev/null

and the fix for my sway sleep+lock command:

bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock; gpg-connect-agent updatestartuptty /bye > /dev/null'"

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

How to run a command as a specific user in an init script?

If you have start-stop-daemon

start-stop-daemon --start --quiet -u username -g usergroup --exec command ...

Cast Double to Integer in Java

Indeed, the simplest way is to use intValue(). However, this merely returns the integer part; it does not do any rounding. If you want the Integer nearest to the Double value, you'll need to do this:

Integer integer = Integer.valueOf((int) Math.round(myDouble)));

And don't forget the null case:

Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));

Math.round() handles odd duck cases, like infinity and NaN, with relative grace.

read.csv warning 'EOF within quoted string' prevents complete reading of file

I had the similar problem: EOF -warning and only part of data was loading with read.csv(). I tried the quotes="", but it only removed the EOF -warning.

But looking at the first row that was not loading, I found that there was a special character, an arrow ? (hexadecimal value 0x1A) in one of the cells. After deleting the arrow I got the data to load normally.

How to listen for changes to a MongoDB collection?

Since MongoDB 3.6 there will be a new notifications API called Change Streams which you can use for this. See this blog post for an example. Example from it:

cursor = client.my_db.my_collection.changes([
    {'$match': {
        'operationType': {'$in': ['insert', 'replace']}
    }},
    {'$match': {
        'newDocument.n': {'$gte': 1}
    }}
])

# Loops forever.
for change in cursor:
    print(change['newDocument'])

Can I write native iPhone apps using Python?

2019 Update:

While Python-iOS development is relatively immature and likely will prevent (afaik) your app from having native UI and functionality that could be achieved in an Apple-supported development language, Apple now seems to allow embedding Python interpreters in Native Swift/Obj-C apps.

This supports importing Python libraries and running Python scripts (even with supplied command-line arguments) directly from your Native Swift/Obj-C code.

My company is actually wrapping our infrastructure (originally written in Python) in a native iOS application! It works very well and communication between the parts can be easily achieved via a client-server model.

Here is a nice library by Beeware with a cookiecutter template if you want to try and run Python scripts in your iOS app: https://github.com/beeware/Python-Apple-support/tree/3.6.

What is the meaning of "Failed building wheel for X" in pip install?

Error :

System : aws ec2 instance (t2 small)

issue : while installing opencv python via

pip3 install opencv-python

  Problem with the CMake installation, aborting build. CMake executable is cmake
  
  ----------------------------------------
  Failed building wheel for opencv-python
  Running setup.py clean for opencv-python

What worked for me

pip3 install --upgrade pip setuptools wheel

After this you still might received fallowing error error

    from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

Installing libgl solved the error for me.

sudo apt update
sudo apt install libgl1-mesa-glx

Hope this helps

what is the difference between OLE DB and ODBC data sources?

ODBC and OLE DB are two competing data access technologies. Specifically regarding SQL Server, Microsoft has promoted both of them as their Preferred Future Direction - though at different times.

ODBC

ODBC is an industry-wide standard interface for accessing table-like data. It was primarily developed for databases and presents data in collections of records, each of which is grouped into a collection of fields. Each field has its own data type suitable to the type of data it contains. Each database vendor (Microsoft, Oracle, Postgres, …) supplies an ODBC driver for their database.

There are also ODBC drivers for objects which, though they are not database tables, are sufficiently similar that accessing data in the same way is useful. Examples are spreadsheets, CSV files and columnar reports.

OLE DB

OLE DB is a Microsoft technology for access to data. Unlike ODBC it encompasses both table-like and non-table-like data such as email messages, web pages, Word documents and file directories. However, it is procedure-oriented rather than object-oriented and is regarded as a rather difficult interface with which to develop access to data sources. To overcome this, ADO was designed to be an object-oriented layer on top of OLE DB and to provide a simpler and higher-level – though still very powerful – way of working with it. ADO’s great advantage it that you can use it to manipulate properties which are specific to a given type of data source, just as easily as you can use it to access those properties which apply to all data source types. You are not restricted to some unsatisfactory lowest common denominator.

While all databases have ODBC drivers, they don’t all have OLE DB drivers. There is however an interface available between OLE and ODBC which can be used if you want to access them in OLE DB-like fashion. This interface is called MSDASQL (Microsoft OLE DB provider for ODBC).

SQL Server Data Access Technologies

Since SQL Server is (1) made by Microsoft, and (2) the Microsoft database platform, both ODBC and OLE DB are a natural fit for it.

ODBC

Since all other database platforms had ODBC interfaces, Microsoft obviously had to provide one for SQL Server. In addition to this, DAO, the original default technology in Microsoft Access, uses ODBC as the standard way of talking to all external data sources. This made an ODBC interface a sine qua non. The version 6 ODBC driver for SQL Server, released with SQL Server 2000, is still around. Updated versions have been released to handle the new data types, connection technologies, encryption, HA/DR etc. that have appeared with subsequent releases. As of 09/07/2018 the most recent release is v13.1 “ODBC Driver for SQL Server”, released on 23/03/2018.

OLE DB

This is Microsoft’s own technology, which they were promoting strongly from about 2002 – 2005, along with its accompanying ADO layer. They were evidently hoping that it would become the data access technology of choice. (They even made ADO the default method for accessing data in Access 2002/2003.) However, it eventually became apparent that this was not going to happen for a number of reasons, such as:

  1. The world was not going to convert to Microsoft technologies and away from ODBC;
  2. DAO/ODBC was faster than ADO/OLE DB and was also thoroughly integrated into MS Access, so wasn’t going to die a natural death;
  3. New technologies that were being developed by Microsoft, specifically ADO.NET, could also talk directly to ODBC. ADO.NET could talk directly to OLE DB as well (thus leaving ADO in a backwater), but it was not (unlike ADO) solely dependent on it.

For these reasons and others, Microsoft actually deprecated OLE DB as a data access technology for SQL Server releases after v11 (SQL Server 2012). For a couple of years before this point, they had been producing and updating the SQL Server Native Client, which supported both ODBC and OLE DB technologies. In late 2012 however, they announced that they would be aligning with ODBC for native relational data access in SQL Server, and encouraged everybody else to do the same. They further stated that SQL Server releases after v11/SQL Server 2012 would actively not support OLE DB!

This announcement provoked a storm of protest. People were at a loss to understand why MS was suddenly deprecating a technology that they had spent years getting them to commit to. In addition, SSAS/SSRS and SSIS, which were MS-written applications intimately linked to SQL Server, were wholly or partly dependent on OLE DB. Yet another complaint was that OLE DB had certain desirable features which it seemed impossible to port back to ODBC – after all, OLE DB had many good points.

In October 2017, Microsoft relented and officially un-deprecated OLE DB. They announced the imminent arrival of a new driver (MSOLEDBSQL) which would have the existing feature set of the Native Client 11 and would also introduce multi-subnet failover and TLS 1.2 support. The driver was released in March 2018.

Child with max-height: 100% overflows parent

Here is a solution for a recently opened question marked as a duplicate of this question. The <img> tag was exceeding the max-height of the parent <div>.

Broken: Fiddle

Working: Fiddle

In this case, adding display:flex to the 2 parent <div> tags was the answer

how to sort an ArrayList in ascending order using Collections and Comparator

Sort By Value

  public Map sortByValue(Map map, final boolean ascending) {
            Map result = new LinkedHashMap();
            try {
                List list = new LinkedList(map.entrySet());

                Collections.sort(list, new Comparator() {
                    @Override
                    public int compare(Object object1, Object object2) {
                        if (ascending)
                            return ((Comparable) ((Map.Entry) (object1)).getValue())
                                    .compareTo(((Map.Entry) (object2)).getValue());
                        else
                            return ((Comparable) ((Map.Entry) (object2)).getValue())
                                    .compareTo(((Map.Entry) (object1)).getValue());

                    }
                });

                for (Iterator it = list.iterator(); it.hasNext();) {
                    Map.Entry entry = (Map.Entry) it.next();
                    result.put(entry.getKey(), entry.getValue());
                }

            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }

            return result;
        }

Get resultset from oracle stored procedure

Oracle is not sql server. Try the following in SQL Developer

variable rc refcursor;
exec testproc(:rc2);
print rc2

How to start an application without waiting in a batch file?

If start can't find what it's looking for, it does what you describe.

Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).

Unix shell script find out which directory the script file resides?

This one-liner tells where the shell script is, does not matter if you ran it or if you sourced it. Also, it resolves any symbolic links involved, if that is the case:

dir=$(dirname $(test -L "$BASH_SOURCE" && readlink -f "$BASH_SOURCE" || echo "$BASH_SOURCE"))

By the way, I suppose you are using /bin/bash.

Android 6.0 multiple permissions

This is what I have done in my activity. Hoping will be helpful. I am asking for camera and microphone permissions.

public class ActiveCallActivity extends AppCompatActivity {
    .....

    private static final String cameraPermissionKey = "cameraPermission";
    private static final String microphonePermissionkey = "microphonePermission";

    private static ArrayList<String> permissionsQueue = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        .....
        // in ValidationCheckersAndValidators simply checking if have permission or not.
        if(ValidationCheckersAndValidators.haveCameraPermission(this)) performHaveCameraPermissionLayout(); else performHaveNoCameraPermissionLayout();
        if(ValidationCheckersAndValidators.haveMicrophonePermission(this)) performHaveMicrophonePermissionLayout(); else performHaveNoMicrophonePermissionLayout();

    }

    private void performHaveNoCameraPermissionLayout() {
        .....
        permissionsQueue.add(cameraPermissionKey);
    }

    private void performHaveNoMicrophonePermissionLayout() {
        .....
        permissionsQueue.add(microphonePermissionkey);
    }

    @Override
    protected void onResume() {
        super.onResume();

        .....
        passThroughPermissionsQueue();
    }

    private void passThroughPermissionsQueue() {
        if(!permissionsQueue.isEmpty()) {
            String permissionKey = permissionsQueue.remove(0);
            switch (permissionKey) {
                case cameraPermissionKey: {
                    ValidationCheckersAndValidators.requestForCameraPermission(this);
                    return;
                }
                case microphonePermissionkey: {
                    ValidationCheckersAndValidators.requestForMicrophonePermission(this);
                    return;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case cameraPermissionRequestCode: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    performHaveCameraPermissionLayout();
                }
                break;
            }
            case microphonePermissionRequestCode: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    performHaveMicrophonePermissionLayout();
                }
                break;
            }
        }
        passThroughPermissionsQueue();
    }
}

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

  1. Check if compatible Mysql for your PHP version is correctly installed. (eg. mysql-installer-community-5.5.40.1.msi for PHP 5.2.10, apache 2.2 and phpMyAdmin 3.5.2)
  2. In your php\php.ini set your loadable php extensions path (eg. extension_dir = "C:\php\ext") (https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)
  3. (In your php\php.ini) check if extension=php_mysqli.dll is uncommented (https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)
  4. Set your php folder (eg."C:\php") and php\ext folder (eg."C:\php\ext") as your runtime environment variable path (https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)
  5. Restart apache service (https://drive.google.com/open?id=1kJF5kxPSrj3LdKWJcJTos9ecKFx0ORAW)

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

Alternative for frames in html5 using iframes

HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".

http://www.w3schools.com/html5/tag_iframe.asp

or you can use

<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>

Calling a class method raises a TypeError in Python

From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

All PLEASE note what Tyler said

Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back

Build Eclipse Java Project from Command Line

This question contains some useful links on headless builds, but they are mostly geared towards building plugins. I'm not sure how much of it can be applied to pure Java projects.

How to rename a table in SQL Server?

To rename a column:

sp_rename 'table_name.old_column_name', 'new_column_name' , 'COLUMN';

To rename a table:

sp_rename 'old_table_name','new_table_name';

Append a Lists Contents to another List C#

GlobalStrings.AddRange(localStrings);

That works.

Documentation: List<T>.AddRange(IEnumerable<T>).

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

RestClientException: Could not extract response. no suitable HttpMessageConverter found

In my case @Ilya Dyoshin's solution didn't work: The mediatype "*" was not allowed. I fix this error by adding a new converter to the restTemplate this way during initialization of the MockRestServiceServer:

  MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = 
                      new MappingJackson2HttpMessageConverter();
  mappingJackson2HttpMessageConverter.setSupportedMediaTypes(
                                    Arrays.asList(
                                       MediaType.APPLICATION_JSON, 
                                       MediaType.APPLICATION_OCTET_STREAM));
  restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
  mockServer = MockRestServiceServer.createServer(restTemplate);

(Based on the solution proposed by Yashwant Chavan on the blog named technicalkeeda)

JN Gerbaux

Font awesome is not showing icon

Check that the path to your CSS file is correct. Rather prefer absolute links, they are easier to understand since we know where we start from and search engines will also prefer them over relative links. And to reduce bandwidth rather use the link from font-awesome servers:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css">

Moreover if you use it, there will be no need of uploading extra fonts to your server and you will be sure that you point to the right CSS file, and you will also benefit from the latest updates instantly.

How to remove blank lines from a Unix file

with awk

awk 'NF > 0' filename

What is the best (and safest) way to merge a Git branch into master?

Neither a rebase nor a merge should overwrite anyone's changes (unless you choose to do so when resolving a conflict).

The usual approach while developing is

git checkout master
git pull
git checkout test
git log master.. # if you're curious
git merge origin/test # to update your local test from the fetch in the pull earlier

When you're ready to merge back into master,

git checkout master
git log ..test # if you're curious
git merge test
git push

If you're worried about breaking something on the merge, git merge --abort is there for you.

Using push and then pull as a means of merging is silly. I'm also not sure why you're pushing test to origin.

Cannot create SSPI context

First thing you should do is go into the logs (Management\SQL Server Logs) and see if SQL Server successfully registered the Service Principal Name (SPN). If you see some sort of error (The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service) then you know where to start.

We saw this happen when we changed the account SQL Server was running under. Resetting it to Local System Account solved the problem. Microsoft also has a guide on manually configuring the SPN.

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

I was hitting the same issue. Added mysql service port number(3307), resolved the issue.

conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/?" + "user=root&password=password");

Visual Studio Code always asking for git credentials

Use ssh instead of http/https.

You will need to set ssh keys on your local machine, upload them to your git server and replace the url form http:// to git:// and you will not need to use passwords anymore.

If you cant use ssh add this to your config:

[credential "https://example.com"]
    username = me

documents are here.


Using ssh key in github


Simply follow those steps and you will set up your ssh key in no time:

  • Generate a new ssh key (or skip this step if you already have a key)
    ssh-keygen -t rsa -C "your@email"

  • Once you have your key set in home/.ssh directory (or Users/<your user>.ssh under windows), open it and copy the content


How to add sh key to github account?

  • Login to github account
  • Click on the rancher on the top right (Settings)
    github account settigns
  • Click on the SSH keys
    ssh key section
  • Click on the Add ssh key
    Add ssh key
  • Paste your key and save

And you all set to go :-)

How to comment out a block of code in Python

In Eclipse using PyDev, you can select a code block and press Ctrl + #.

List of special characters for SQL LIKE clause

Sybase :

%              : Matches any string of zero or more characters.
_              : Matches a single character.
[specifier]    : Brackets enclose ranges or sets, such as [a-f] 
                 or [abcdef].Specifier  can take two forms:

                 rangespec1-rangespec2: 
                   rangespec1 indicates the start of a range of characters.
                   - is a special character, indicating a range.
                   rangespec2 indicates the end of a range of characters.

                 set: 
                  can be composed of any discrete set of values, in any 
                  order, such as [a2bR].The range [a-f], and the 
                  sets [abcdef] and [fcbdae] return the same 
                  set of values.

                 Specifiers are case-sensitive.

[^specifier]    : A caret (^) preceding a specifier indicates 
                  non-inclusion. [^a-f] means "not in the range 
                  a-f"; [^a2bR] means "not a, 2, b, or R."

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

The way I have done this is to give the user permission to the tables that I didn't want them to have access to. Then fine tune the select permission in SSMS by only allowing select permission to the columns that are in my view. This way, the select clause on the table is only limited to the columns that they see in the view anyways.

enter image description here

Shaji

How to parse XML using shellscript?

Do you have xml_grep installed? It's a perl based utility standard on some distributions (it came pre-installed on my CentOS system). Rather than giving it a regular expression, you give it an xpath expression.

Java equivalent to Explode and Implode(PHP)

Good alternatives are the String.split and StringUtils.join methods.

Explode :

String[] exploded="Hello World".split(" ");

Implode :

String imploded=StringUtils.join(new String[] {"Hello", "World"}, " ");

Keep in mind though that StringUtils is in an external library.

Lollipop : draw behind statusBar with its color set to transparent

This worked for my case


// Create/Set toolbar as actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

// Check if the version of Android is Lollipop or higher
if (Build.VERSION.SDK_INT >= 21) {

    // Set the status bar to dark-semi-transparentish
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
            WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

    // Set paddingTop of toolbar to height of status bar.
    // Fixes statusbar covers toolbar issue
    toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
}

// A method to find height of the status bar
public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

For more information about working with statusBars: youtube.com/watch?v=_mGDMVRO3iE


How to read string from keyboard using C?

I cannot see why there is a recommendation to use scanf() here. scanf() is safe only if you add restriction parameters to the format string - such as %64s or so.

A much better way is to use char * fgets ( char * str, int num, FILE * stream );.

int main()
{
    char data[64];
    if (fgets(data, sizeof data, stdin)) {
        // input has worked, do something with data
    }
}

(untested)

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Laravel - Return json along with http status code

I think it is better practice to keep your response under single control and for this reason I found out the most official solution.

response()->json([...])
    ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);

add this after namespace declaration:

use Illuminate\Http\Response;

Java Embedded Databases Comparison

I am a big fan of DB4O for both .Net and Java.

Performance has become much better since the early releases. The licensing model isnt too bad, either. I particularly like the options available for querying your objects. Query by example is very powerful and easy to get used to.

How to set a class attribute to a Symfony2 form input

You can add it in the options of your form class:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\MyEntity',
        'attr' => array(
            'class' => 'form-horizontal'
        )
    ));
}

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

Install opencv for Python 3.3

Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:

import cv2 as cv

JavaScript: Class.method vs. Class.prototype.method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

Consider this example:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

How to round up the result of integer division?

For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):

int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);

In java you should do the same with Math.ceil().

How can I close a window with Javascript on Mozilla Firefox 3?

From a user experience stand-point, you don't want a major action to be done passively.

Something major like a window close should be the result of an action by the user.

KeyListener, keyPressed versus keyTyped

keyPressed - when the key goes down
keyReleased - when the key comes up
keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.

I personally would use keyReleased for this. It will fire only when they lift their finger up.

Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.

ReCaptcha API v2 Styling

I came across this answer trying to style the ReCaptcha v2 for a site that has a light and a dark mode. Played around some more and discovered that besides transform, filter is also applied to iframe elements so ended up using the default/light ReCaptcha and doing this when the user is in dark mode:

.g-recaptcha {
    filter: invert(1) hue-rotate(180deg);
}

The hue-rotate(180deg) makes it so that the logo is still blue and the check-mark is still green when the user clicks it, while keeping white invert()'ed to black and vice versa.

Didn't see this in any answer or comment so decided to share even if this is an old thread.

Checkbox value true/false

Try this

_x000D_
_x000D_
$("#checkbox1").is(':checked', function(){_x000D_
  $("#checkbox1").prop('checked', true);_x000D_
});_x000D_
      
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">
_x000D_
_x000D_
_x000D_

How to convert std::string to lower case?

Is there an alternative which works 100% of the time?

No

There are several questions you need to ask yourself before choosing a lowercasing method.

  1. How is the string encoded? plain ASCII? UTF-8? some form of extended ASCII legacy encoding?
  2. What do you mean by lower case anyway? Case mapping rules vary between languages! Do you want something that is localised to the users locale? do you want something that behaves consistently on all systems your software runs on? Do you just want to lowercase ASCII characters and pass through everything else?
  3. What libraries are available?

Once you have answers to those questions you can start looking for a soloution that fits your needs. There is no one size fits all that works for everyone everywhere!

Dynamic Height Issue for UITableView Cells (Swift)

This is simple when doing 2 things:

  1. setting the automatic height
tableView.rowHeight = UITableView.automaticDimension
  1. creating all TableViewCells with FULL constraints from top to bottom. The last element MUST define some bottom spacing to end the cell.

So the layout engine can compute the cell heigth and apply the value correctly.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

How to find out whether a file is at its `eof`?

fp.read() reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception.

When reading a file in chunks rather than with read(), you know you've hit EOF when read returns less than the number of bytes you requested. In that case, the following read call will return the empty string (not None). The following loop reads a file in chunks; it will call read at most once too many.

assert n > 0
while True:
    chunk = fp.read(n)
    if chunk == '':
        break
    process(chunk)

Or, shorter:

for chunk in iter(lambda: fp.read(n), ''):
    process(chunk)

Remove all special characters with RegExp

why dont you do something like:

re = /^[a-z0-9 ]$/i;
var isValid = re.test(yourInput);

to check if your input contain any special char

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

How to easily resize/optimize an image size with iOS?

I developed an ultimate solution for image scaling in Swift.

You can use it to resize image to fill, aspect fill or aspect fit specified size.

You can align image to center or any of four edges and four corners.

And also you can trim extra space which is added if aspect ratios of original image and target size are not equal.

enum UIImageAlignment {
    case Center, Left, Top, Right, Bottom, TopLeft, BottomRight, BottomLeft, TopRight
}

enum UIImageScaleMode {
    case Fill,
    AspectFill,
    AspectFit(UIImageAlignment)
}

extension UIImage {
    func scaleImage(width width: CGFloat? = nil, height: CGFloat? = nil, scaleMode: UIImageScaleMode = .AspectFit(.Center), trim: Bool = false) -> UIImage {
        let preWidthScale = width.map { $0 / size.width }
        let preHeightScale = height.map { $0 / size.height }
        var widthScale = preWidthScale ?? preHeightScale ?? 1
        var heightScale = preHeightScale ?? widthScale
        switch scaleMode {
        case .AspectFit(_):
            let scale = min(widthScale, heightScale)
            widthScale = scale
            heightScale = scale
        case .AspectFill:
            let scale = max(widthScale, heightScale)
            widthScale = scale
            heightScale = scale
        default:
            break
        }
        let newWidth = size.width * widthScale
        let newHeight = size.height * heightScale
        let canvasWidth = trim ? newWidth : (width ?? newWidth)
        let canvasHeight = trim ? newHeight : (height ?? newHeight)
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(canvasWidth, canvasHeight), false, 0)

        var originX: CGFloat = 0
        var originY: CGFloat = 0
        switch scaleMode {
        case .AspectFit(let alignment):
            switch alignment {
            case .Center:
                originX = (canvasWidth - newWidth) / 2
                originY = (canvasHeight - newHeight) / 2
            case .Top:
                originX = (canvasWidth - newWidth) / 2
            case .Left:
                originY = (canvasHeight - newHeight) / 2
            case .Bottom:
                originX = (canvasWidth - newWidth) / 2
                originY = canvasHeight - newHeight
            case .Right:
                originX = canvasWidth - newWidth
                originY = (canvasHeight - newHeight) / 2
            case .TopLeft:
                break
            case .TopRight:
                originX = canvasWidth - newWidth
            case .BottomLeft:
                originY = canvasHeight - newHeight
            case .BottomRight:
                originX = canvasWidth - newWidth
                originY = canvasHeight - newHeight
            }
        default:
            break
        }
        self.drawInRect(CGRectMake(originX, originY, newWidth, newHeight))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

There are examples of applying this solution below.

Gray rectangle is target site image will be resized to. Blue circles in light blue rectangle is the image (I used circles because it's easy to see when it's scaled without preserving aspect). Light orange color marks areas that will be trimmed if you pass trim: true.

Aspect fit before and after scaling:

Aspect fit 1 (before) Aspect fit 1 (after)

Another example of aspect fit:

Aspect fit 2 (before) Aspect fit 2 (after)

Aspect fit with top alignment:

Aspect fit 3 (before) Aspect fit 3 (after)

Aspect fill:

Aspect fill (before) Aspect fill (after)

Fill:

Fill (before) Fill (after)

I used upscaling in my examples because it's simpler to demonstrate but solution also works for downscaling as in question.

For JPEG compression you should use this :

let compressionQuality: CGFloat = 0.75 // adjust to change JPEG quality
if let data = UIImageJPEGRepresentation(image, compressionQuality) {
  // ...
}

You can check out my gist with Xcode playground.

How can I exclude directories from grep -R?

If you want to exclude multiple directories:

"r" for recursive, "l" to print only names of files containing matches and "i" to ignore case distinctions :

grep -rli --exclude-dir={dir1,dir2,dir3} keyword /path/to/search

Example : I want to find files that contain the word 'hello'. I want to search in all my linux directories except proc directory, boot directory, sys directory and root directory :

grep -rli --exclude-dir={proc,boot,root,sys} hello /

Note : The example above needs to be root

Note 2 (according to @skplunkerin) : do not add spaces after the commas in {dir1,dir2,dir3}

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

JavaScript regex for alphanumeric string with length of 3-5 chars

First this script test the strings N having chars from 3 to 5.

For multi language (arabic, Ukrainian) you Must use this

var regex = /^([a-zA-Z0-9_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]+){3,5}$/;  regex.test('?????');

Other wise the below is for English Alphannumeric only

/^([a-zA-Z0-9_-]){3,5}$/

P.S the above dose not accept special characters

one final thing the above dose not take space as test it will fail if there is space if you want space then add after the 0-9\s

\s

And if you want to check lenght of all string add dot .

var regex = /^([a-zA-Z0-9\s@,!=%$#&_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]).{1,30}$/;

What is the "-->" operator in C/C++?

This --> is not an operator at all. We have an operator like ->, but not like -->. It is just a wrong interpretation of while(x-- >0) which simply means x has the post decrement operator and this loop will run till it is greater than zero.

Another simple way of writing this code would be while(x--). The while loop will stop whenever it gets a false condition and here there is only one case, i.e., 0. So it will stop when the x value is decremented to zero.

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

How do I install and use curl on Windows?

Follow download wizard

Follow the screens one by one to select type of package (curl executable), OS (Win64), flavor (Generic), CPU (x86_64) and the download link.

unzip download and find curl.exe (I found it in src folder, one may find it in bin folder for different OS/flavor)

To make it available from the command line, add the executable path to the system path (Adding directory to PATH Environment Variable in Windows).

Enjoy curl.

How is TeamViewer so fast?

would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)

You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).

They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.

I've only ever seen it do this when a client has been behind double-NAT, though.

How to change background color in android app

Another way, go to layout -> your .xml file -> design view .Then go component tree and select layout you want to change color . In below component tree there is properties section .Select background in the properties section (In picture section 1). Then click section 2 in picture . Then Resources window will be open .From that select color menu .Then choose color you want .enter image description here

Transfer data from one HTML file to another

Try this code: In testing.html

function testJS() {
    var b = document.getElementById('name').value,
        url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);

    document.location.href = url;
}

And in next.html:

window.onload = function () {
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('here').innerHTML = data.name;
}

Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc. Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.

PS. i'm an non-native english speaker, will you please correct my message, if necessary

Delayed rendering of React components

We can solve this using Hooks:

First we'll need a timeout hook for the delay.

This one is inspired by Dan Abramov's useInterval hook (see Dan's blog post for an in depth explanation), the differences being:

  1. we use we setTimeout not setInterval
  2. we return a reset function allowing us to restart the timer at any time

_x000D_
_x000D_
import { useEffect, useRef, useCallback } from 'react';_x000D_
_x000D_
const useTimeout = (callback, delay) => {_x000D_
  // save id in a ref_x000D_
  const timeoutId = useRef('');_x000D_
_x000D_
  // save callback as a ref so we can update the timeout callback without resetting the clock_x000D_
  const savedCallback = useRef();_x000D_
  useEffect(_x000D_
    () => {_x000D_
      savedCallback.current = callback;_x000D_
    },_x000D_
    [callback],_x000D_
  );_x000D_
_x000D_
  // clear the timeout and start a new one, updating the timeoutId ref_x000D_
  const reset = useCallback(_x000D_
    () => {_x000D_
      clearTimeout(timeoutId.current);_x000D_
_x000D_
      const id = setTimeout(savedCallback.current, delay);_x000D_
      timeoutId.current = id;_x000D_
    },_x000D_
    [delay],_x000D_
  );_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      if (delay !== null) {_x000D_
        reset();_x000D_
_x000D_
        return () => clearTimeout(timeoutId.current);_x000D_
      }_x000D_
    },_x000D_
    [delay, reset],_x000D_
  );_x000D_
_x000D_
  return { reset };_x000D_
};
_x000D_
_x000D_
_x000D_

and now we need a hook which will capture previous children and use our useTimeout hook to swap in the new children after a delay

_x000D_
_x000D_
import { useState, useEffect } from 'react';_x000D_
_x000D_
const useDelayNextChildren = (children, delay) => {_x000D_
  const [finalChildren, setFinalChildren] = useState(children);_x000D_
_x000D_
  const { reset } = useTimeout(() => {_x000D_
    setFinalChildren(children);_x000D_
  }, delay);_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      reset();_x000D_
    },_x000D_
    [reset, children],_x000D_
  );_x000D_
_x000D_
  return finalChildren || children || null;_x000D_
};
_x000D_
_x000D_
_x000D_

Note that the useTimeout callback will always have the latest children, so even if we attempt to render multiple different new children within the delay time, we'll always get the latest children once the timeout finally completes.

Now in your case, we want to also delay the initial render, so we make this change:

_x000D_
_x000D_
const useDelayNextChildren = (children, delay) => {_x000D_
  const [finalChildren, setFinalChildren] = useState(null); // initial state set to null_x000D_
_x000D_
  // ... stays the same_x000D_
_x000D_
  return finalChildren || null;  // remove children from return_x000D_
};
_x000D_
_x000D_
_x000D_

and using the above hook, your entire child component becomes

_x000D_
_x000D_
import React, { memo } from 'react';_x000D_
import { useDelayNextChildren } from 'hooks';_x000D_
_x000D_
const Child = ({ delay }) => useDelayNextChildren(_x000D_
  <div>_x000D_
    ... Child JSX goes here_x000D_
    ... etc_x000D_
  </div>_x000D_
  , delay_x000D_
);_x000D_
_x000D_
export default memo(Child);
_x000D_
_x000D_
_x000D_

or if you prefer: ( dont say i havent given you enough code ;) )

_x000D_
_x000D_
const Child = ({ delay }) => {_x000D_
  const render = <div>... Child JSX goes here ... etc</div>;_x000D_
_x000D_
  return useDelayNextChildren(render, delay);_x000D_
};
_x000D_
_x000D_
_x000D_

which will work exactly the same in the Parent render function as in the accepted answer

...

except the delay will be the same on every subsequent render too,

AND we used hooks, so that stateful logic is reusable across any component

...

...

use hooks. :D

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How to create JSON Object using String?

If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

Writing List of Strings to Excel CSV File in Python

The csv.writer writerow method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

Do either:

import csv
RESULTS = [
    ['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerows(RESULTS)

or:

import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerow(RESULT)

Maven – Always download sources and javadocs

Just consolidating and prepared the single command to address source and docs download...

mvn dependency:sources dependency:resolve -Dclassifier=javadoc

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

Is there a Python equivalent of the C# null-coalescing operator?

In addition to Juliano's answer about behavior of "or": it's "fast"

>>> 1 or 5/0
1

So sometimes it's might be a useful shortcut for things like

object = getCachedVersion() or getFromDB()

Structure of a PDF file?

Here's the raw reference of PDF 1.7, and here's an article describing the structure of a PDF file. If you use Vim, the pdftk plugin is a good way to explore the document in an ever-so-slightly less raw form, and the pdftk utility itself (and its GPL source) is a great way to tease documents apart.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Mac OS X and multiple Java versions

Here's a more DRY version for bash (Based on Vegard's answer)

Replace 1.7 and 1.8 with whatever versions you are interested with and you'll get an alias called 'javaX'; where 'X' is the java version (7 / 8 in the snippet below) that will allow you to easily switch versions

for version in 1.7 1.8; do
    v="${version: -1}"
    h=JAVA_"$v"_HOME

    export "$h"=$(/usr/libexec/java_home -v $version)

    alias "java$v"="export JAVA_HOME=\$$h"
done

Getting files by creation date in .NET

If the performance is an issue, you can use this command in MS_DOS:

dir /OD >d:\dir.txt

This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.

Escaping double quotes in JavaScript onClick event handler

While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:

<script type="text/javascript">
function parse(a, b, c) {
    alert(c);
  }

</script>

<a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>

The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

How to import image (.svg, .png ) in a React Component

Solved the problem, when moved the folder with the image in src folder. Then I turned to the image (project created through "create-react-app")
let image = document.createElement("img"); image.src = require('../assets/police.png');

What is an NP-complete in computer science?

NP-Complete is a class of problems.

The class P consists of those problems that are solvable in polynomial time. For example, they could be solved in O(nk) for some constant k, where n is the size of the input. Simply put, you can write a program that will run in reasonable time.

The class NP consists of those problems that are verifiable in polynomial time. That is, if we are given a potential solution, then we could check if the given solution is correct in polynomial time.

Some examples are the Boolean Satisfiability (or SAT) problem, or the Hamiltonian-cycle problem. There are many problems that are known to be in the class NP.

NP-Complete means the problem is at least as hard as any problem in NP.

It is important to computer science because it has been proven that any problem in NP can be transformed into another problem in NP-complete. That means that a solution to any one NP-complete problem is a solution to all NP problems.

Many algorithms in security depends on the fact that no known solutions exist for NP hard problems. It would definitely have a significant impact on computing if a solution were found.

How do you properly use namespaces in C++?

You can also contain "using namespace ..." inside a function for example:

void test(const std::string& s) {
    using namespace std;
    cout << s;
}