Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
From Python documentation -> 8.3 Handling Exceptions:
A
try
statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:except (RuntimeError, TypeError, NameError): pass
Note that the parentheses around this tuple are required, because except
ValueError, e:
was the syntax used for what is normally written asexcept ValueError as e:
in modern Python (described below). The old syntax is still supported for backwards compatibility. This meansexcept RuntimeError, TypeError
is not equivalent toexcept (RuntimeError, TypeError):
but toexcept RuntimeError as
TypeError:
which is not what you want.
Tagname you should mentioned like that "option", if text with space we can use this method it should work.
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
if("Germany".equals(option.getText().trim()))
option.click();
}
It should be MM
for months. You are asking for minutes.
DateTime.Now.ToString("dd/MM/yyyy");
See Custom Date and Time Format Strings on MSDN for details.
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
As of June 2019 this setting can be found through searching 'Panel' - if you want to change the default there is an option for it as shown in the screenshot:
jQuery UI Dialog right here: http://jqueryui.com/demos/dialog/
After reading all these explanations I thought I'd weigh in with the method my professor used to explain the Towers of Hanoi recursive solution. Here is the algorithm again with n representing the number of rings, and A, B, C representing the pegs. The first parameter of the function is the number of rings, second parameter represents the source peg, the third is the destination peg, and fourth is the spare peg.
procedure Hanoi(n, A, B, C);
if n == 1
move ring n from peg A to peg B
else
Hanoi(n-1, A, C, B);
move ring n-1 from A to C
Hanoi(n-1, C, B, A);
end;
I was taught in graduate school to never to be ashamed to think small. So, let's look at this algorithm for n = 5. The question to ask yourself first is if I want to move the 5th ring from A to B, where are the other 4 rings? If the 5th ring occupies peg A and we want to move it to peg B, then the other 4 rings can only be on peg C. In the algorithm above the function Hanoi (n-1, A, C, B) is trying to move all those 4 other rings on to peg C, so ring 5 will be able to move from A to B. Following this algorithm we look at n = 4. If ring 4 will be moved from A to C, where are rings 3 and smaller? They can only be on peg B. Next, for n = 3, if ring 3 will be moved from A to B, where are rings 2 and 1? On peg C of course. If you continue to follow this pattern you can visualize what the recursive algorithm is doing. This approach differs from the novice's approach in that it looks at the last disk first and the first disk last.
data.reshape((50,1104,-1))
works for me
I could see that there is a better library than the apache commons exec library. You can execute your job using Java Secure Shell (JSch).
I had the same problem. I used JSch to solve this problem. Apache commons had some issues running commands on a different server. Plus JSch gave me result and errors InputStreams. I found it more elegant. Sample solution can be found here : http://wiki.jsch.org/index.php?Manual%2FExamples%2FJschExecExample
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.commons.exec.*;
import com.jcraft.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.ChannelExec;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
public class exec_linux_cmd {
public HashMap<String,List<String>> exec_cmd (
String USERNAME,
String PASSWORD,
String host,
int port,
String cmd)
{
List<String> result = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
HashMap<String,List<String>> result_map = new HashMap<String,List<String>>();
//String line = "echo `eval hostname`";
try{
JSch jsch = new JSch();
/*
* Open a new session, with your username, host and port
* Set the password and call connect.
* session.connect() opens a new connection to remote SSH server.
* Once the connection is established, you can initiate a new channel.
* this channel is needed to connect and remotely execute the program
*/
Session session = jsch.getSession(USERNAME, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
//create the excution channel over the session
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
// Gets an InputStream for this channel. All data arriving in as messages from the remote side can be read from this stream.
InputStream in = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
// Set the command that you want to execute
// In our case its the remote shell script
channelExec.setCommand(cmd);
//Execute the command
channelExec.connect();
// read the results stream
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// read the errors stream. This will be null if no error occured
BufferedReader err_reader = new BufferedReader(new InputStreamReader(err));
String line;
//Read each line from the buffered reader and add it to result list
// You can also simple print the result here
while ((line = reader.readLine()) != null)
{
result.add(line);
}
while ((line = err_reader.readLine()) != null)
{
errors.add(line);
}
//retrieve the exit status of the remote command corresponding to this channel
int exitStatus = channelExec.getExitStatus();
System.out.println(exitStatus);
//Safely disconnect channel and disconnect session. If not done then it may cause resource leak
channelExec.disconnect();
session.disconnect();
System.out.println(exitStatus);
result_map.put("result", result);
result_map.put("error", errors);
if(exitStatus < 0){
System.out.println("Done--> " + exitStatus);
System.out.println(Arrays.asList(result_map));
//return errors;
}
else if(exitStatus > 0){
System.out.println("Done -->" + exitStatus);
System.out.println(Arrays.asList(result_map));
//return errors;
}
else{
System.out.println("Done!");
System.out.println(Arrays.asList(result_map));
//return result;
}
}
catch (Exception e)
{
System.out.print(e);
}
return result_map;
}
//CommandLine commandLine = CommandLine.parse(cmd);
//DefaultExecutor executor = new DefaultExecutor();
//executor.setExitValue(1);
//int exitValue = executor.execute(commandLine);
public static void main(String[] args)
{
//String line = args[0];
final String USERNAME ="abc"; // username for remote host
final String PASSWORD ="abc"; // password of the remote host
final String host = "3.98.22.10"; // remote host address
final int port=22; // remote host port
HashMap<String,List<String>> result = new HashMap<String,List<String>>();
//String cmd = "echo `eval hostname`"; // command to execute on remote host
exec_linux_cmd ex = new exec_linux_cmd();
result = ex.exec_cmd(USERNAME, PASSWORD , host, port, cmd);
System.out.println("Result ---> " + result.get("result"));
System.out.println("Error Msg ---> " +result.get("error"));
//System.out.println(Arrays.asList(result));
/*
for (int i =0; i < result.get("result").size();i++)
{
System.out.println(result.get("result").get(i));
}
*/
}
}
EDIT 1: In order to find your process (if its a long-running one) being executed on Unix, use the ps -aux | grep java
. The process ID should be listed alongwith the unix command you are executing.
Hibernate 4.3 is the first version to implement the JPA 2.1 spec (part of Java EE 7). And it's thus expecting the JPA 2.1 library in the classpath, not the JPA 2.0 library. That's why you get this exception: Table.indexes() is a new attribute of Table, introduced in JPA 2.1
I found code which converts the json string to NSDictionary or NSArray. Just add the extension.
SWIFT 3.0
HOW TO USE
let jsonData = (convertedJsonString as! String).parseJSONString
EXTENSION
extension String
{
var parseJSONString: AnyObject?
{
let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let jsonData = data
{
// Will return an object or nil if JSON decoding fails
do
{
let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
if let jsonResult = message as? NSMutableArray {
return jsonResult //Will return the json array output
} else if let jsonResult = message as? NSMutableDictionary {
return jsonResult //Will return the json dictionary output
} else {
return nil
}
}
catch let error as NSError
{
print("An error occurred: \(error)")
return nil
}
}
else
{
// Lossless conversion of the string was not possible
return nil
}
}
}
I haven't ever seen such a thing, but there is this dev tool that includes a syntax checker for oracle, mysql, db2, and sql server... http://www.sqlparser.com/index.php
However this seems to be just the library. You'd need to build an app to leverage the parser to do what you want. And the Enterprise edition that includes all of the databases would cost you $450... ouch!
EDIT: And, after saying that - it looks like someone might already have done what you want using that library: http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl
The online tool doesn't automatically check against each DB though, you need to run each manually. Nor can I say how good it is at checking the syntax. That you'd need to investigate yourself.
require 'pathname'
Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>
I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
according to mysql documentation none of these works! People pay attention! so we will upload test.sql into the test_db type this into the shell:
mysql --user=user_name --password=yourpassword test_db < d:/test.sql
If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data
and you have some function find_definition()
which gets the definition, you can do something like the following:
for word in data:
data[word] = find_definition(word)
The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this
FOR SQL SERVER 2005 and above
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified =(int)cmd.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
return modified;
}
}
FOR previous versions
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified = Convert.ToInt32(cmd.ExecuteScalar());
if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
}
We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 ¶m2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detaill click here
So the query I was assigned to optimize was written with two CTEs in SQL server. It was taking 28sec.
I spent two minutes converting them to temp tables and the query took 3 seconds
I added an index to the temp table on the field it was being joined on and got it down to 2 seconds
Three minutes of work and now its running 12x faster all by removing CTE. I personally will not use CTEs ever they are tougher to debug as well.
The crazy thing is the CTEs were both only used once and still putting an index on them proved to be 50% faster.
You could copy the XAMPP shortcut into "Local Disk C /users/YourUserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Start-up"...
This will make the control panel start up with the computer. Then if you were to select the configuration in the top right hand corner of the control panel you can make Apache and MySQL auto start... This is a quite long-winded get around, but it works for Windows 10.
Swift 4, 4.2 and 5
Play audio from URL and from your project (Local File)
import UIKit
import AVFoundation
class ViewController: UIViewController{
var audioPlayer : AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// call what ever function you want.
}
private func playAudioFromURL() {
guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else {
print("error to get the mp3 file")
return
}
do {
audioPlayer = try AVPlayer(url: url as URL)
} catch {
print("audio file error")
}
audioPlayer?.play()
}
private func playAudioFromProject() {
guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
print("error to get the mp3 file")
return
}
do {
audioPlayer = try AVPlayer(url: url)
} catch {
print("audio file error")
}
audioPlayer?.play()
}
}
Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work.
If you want to make it work again, simply re-install.
By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
I'm using a BindingSource with a SqlDataReader behind it and none of the above works for me.
Question for Microsoft: Why does this work:
? lst.SelectedValue
But this doesn't?
? lst.Items[80].Value
I find I have to go back to to the BindingSource object, cast it as a System.Data.Common.DbDataRecord, and then refer to its column name:
? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"]
Now that's just ridiculous.
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
If you want PHP file caching only, you can use eAccelerator directly. Very easy to install and configure, and give great results.
But too bad, they removed the eaccelerator_put and eaccelerator_put from the latest version 0.9.6.
you can use --extra-vars
like this:
$ ansible all --inventory=10.0.1.2, -m ping \
--extra-vars "ansible_user=root ansible_password=yourpassword"
If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.
ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all
This is the jQuery method. Looks like overkill but it calculates the offset.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/dreamerslab/jquery.center/master/jquery.center.js"></script>
<script type="text/javascript">
$(function(){
$('#jquery-center').center();
});
</script>
</head>
<body>
<div id="jquery-center" style="position:absolute;">
<h1>foo</h1>
</div>
</body>
</html>
You can use:
case text1: case text4:
do stuff;
break;
This is my aproximation:
Declare
Variableclob Clob;
Temp_Save Varchar2(32767); //whether it is greater than 4000
Begin
Select reportClob Into Temp_Save From Reporte Where Id=...;
Variableclob:=To_Clob(Temp_Save);
Dbms_Output.Put_Line(Variableclob);
End;
You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)
Or for loops:
z <- 1 ## Initialize
counter <- 1 ## Initialize
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
for (x in 1:32) {
z[counter] <- tmp_int[x,y]
counter <- 1 + counter
}
}
z is a 1d vector.
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
They have no keywords before them. The order is important!
func(1,2,3, "foo")
They have keywords in the front. They can be in any order!
func(foo="bar", baz=5, hello=123)
func(baz=5, foo="bar", hello=123)
You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!
def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)
Change your config.php:
$config['sess_use_database'] = TRUE;
To:
$config['sess_use_database'] = FALSE;
It works for me.
This is the code that i personally use in my sites. Works outside of the box.
<?php
function breadcrumbs($home = 'Home') {
global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
$breadcrumb = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
$root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
$breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
foreach ($breadcrumbs as $crumb) {
$link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
$root_domain .= $crumb . '/';
$breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
}
$breadcrumb .= '</ol>';
$breadcrumb .= '</div>';
$breadcrumb .= '</div>';
return $breadcrumb;
}
echo breadcrumbs();
?>
The css:
.breadcrumb-container {
width: 100%;
background-color: #f8f8f8;
border-bottom-color: 1px solid #f4f4f4;
list-style: none;
margin-top: 72px;
min-height: 25px;
box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
}
.breadcrumb-container li {
display: inline
}
.breadcrumb {
font-size: 12px;
padding-top: 3px
}
.breadcrumb>li:last-child:after {
content: none
}
.breadcrumb>li:last-child {
font-weight: 700;
font-style: italic
}
.breadcrumb>li>i {
margin-right: 3px
}
.breadcrumb>li:after {
font-family: FontAwesome;
content: "\f101";
font-size: 11px;
margin-left: 3px;
margin-right: 3px
}
.breadcrumb>li+li:before {
font-size: 11px;
padding-left: 3px
}
Feel free to play around with the css padding and margins until you get it right for your own site.
I was also having this same error but hopefully after spending 1 day on this error i have got this solution and it got started perfectly and i also hope this works for you guys also...
final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
.stream()
//depending on how you want to join K and V use different delimiter
.map(entry ->
String.join(":", entry.getKey(),entry.getValue()))
.forEach(System.out::println);
There are 2 possible solutions that I personally use
1.without using form
<button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>
2.Using Form
<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}
<button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
</form>
Where urls.py should have this
path('excel/',views1.downloadexcel,name="downloadexcel"),
When the problem is in the recalculation of an IF condition, I add AND(ISDATE(NOW());condition)
so that the cell is forced to recalculate according to
what is set in the Calculation tab in Spreadsheet Settings as explained before.
This works because NOW
is one of the functions that is affected by the Calculation setting and ISDATE(NOW())
always returns TRUE
.
For example, in one of my sheets I had the following condition which I use to check whether a sheet with name stored in C1
is already created:
=IF(ISREF(INDIRECT(C$1&"!A1")); TRUE; FALSE)
In this case C1="February"
, so I expected the condition to become TRUE
when a sheet with this name was created, which didn't happen. To force it to update, I changed the Calculation setting and used:
=IF(AND( ISDATE(NOW()) ; ISREF(INDIRECT(C$1&"!A1")) ); TRUE; FALSE)
This is not REST. You cannot define URIs for resources inside your API. Resource navigation must be hypertext-driven. It's fine if you want pretty URIs and heavy amounts of coupling, but just do not call it REST, because it directly violates the constraints of RESTful architecture.
See this article by the inventor of REST.
I was building a nav menu. I have overflow: hidden
in my nav's css which hid everything. I thought it was a z-index problem, but really I was hiding everything outside my nav.
I see you're having issues with the social share links. I had a similar issue at some point and found this question, but I don't see a complete answer for it. I hope my javascript resolution from below will help:
I had default sharing links that needed to be modified so that the URL that's being shared will have additional UTM parameters concatenated.
My example will be for the Facebook social share link, but it works for all the possible social sharing network links:
The URL that needed to be shared was:
https://mywebsitesite.com/blog/post-name
The default sharing link looked like:
$facebook_default = "https://www.facebook.com/sharer.php?u=https%3A%2F%2mywebsitesite.com%2Fblog%2Fpost-name%2F&t=hello"
I first DECODED it:
console.log( decodeURIComponent($facebook_default) );
=>
https://www.facebook.com/sharer.php?u=https://mywebsitesite.com/blog/post-name/&t=hello
Then I replaced the URL with the encoded new URL (with the UTM parameters concatenated):
console.log( decodeURIComponent($facebook_default).replace( window.location.href, encodeURIComponent(window.location.href+'?utm_medium=social&utm_source=facebook')) );
=>
https://www.facebook.com/sharer.php?u=https%3A%2F%mywebsitesite.com%2Fblog%2Fpost-name%2F%3Futm_medium%3Dsocial%26utm_source%3Dfacebook&t=2018
That's it!
Complete solution:
$facebook_default = $('a.facebook_default_link').attr('href');
$('a.facebook_default_link').attr( 'href', decodeURIComponent($facebook_default).replace( window.location.href, encodeURIComponent(window.location.href+'?utm_medium=social&utm_source=facebook')) );
you can integrate to LDAP or AD as well. It works well.
One more cause for this:
If the routes are overridden with the same URI (Unknowingly), it causes this error:
Eg:
Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('dashboard/', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);
In this case route 'my.dashboard' is invalidate as the both routes has same URI ('dashboard', 'dashboard/')
Solution: You should change the URI for either one
Eg:
Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('home-dashboard', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);
// See the URI changed for this 'home-dashboard'
Hope it helps some once.
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
Here is some information about one more source of the JSESSIONID
cookie:
I was just debugging some Java code that runs on a tomcat server. I was not calling request.getSession()
explicitly anywhere in my code but I noticed that a JSESSIONID
cookie was still being set.
I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.
It appears that, whether you like it or not, if you invoke a JSP from a servlet, JSESSIONID
will get created!
Added: I just found that by adding the following JSP directive:
<%@ page session="false" %>
you can disable the setting of JSESSIONID
by a JSP.
Having some experience of this, you can indeed use C++ code for your "core" code, but you have to use objective-C for anything iPhone specific.
Don't try to force Objective-C to act like C++. At first it will seem to you this is possible, but the resulting code really won't work well with Cocoa, and you will get very confused as to what is going on. Take the time to learn properly, without any C++ around, how to build GUIs and iPhone applications, then link in your C++ base.
Here is what worked for me (Dominic was just one line short).
$url = "";
$options = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n" . // check function.stream-context-create on php.net
"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
)
);
$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);
The previous answer from Andreas_D is good. I'm just going to add that wherever you are displaying the output there will be a font and a character encoding and it may not support some characters.
To work out whether it is Java or your display that is a problem, do this:
for(int i=0;i<str.length();i++) {
char ch = str.charAt(i);
System.out.println(i+" : "+ch+" "+Integer.toHexString(ch)+((ch=='\ufffd') ? " Unknown character" : ""));
}
Java will have mapped any characters it cannot understand to 0xfffd the official character for unknown characters. If you see a '?' in the output, but it is not mapped to 0xfffd, it is your display font or encoding that is the problem, not Java.
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
It's pretty much the same as in Objective-C
let del = UIApplication.sharedApplication().delegate
The composer documentation states that:
After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.
Assuming your "src" dir resides at the same level as "vendor" dir:
the following config is absolutely correct:
{
"autoload": {
"psr-0": {"AppName": "src/"}
}
}
but you must re-update/install dependencies to make it work for you, i.e. run:
php composer.phar update
This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.
Also as noted by @Dom, you can use composer dump-autoload
to update the autoloader without having to go through an update.
This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?
import tkinter
class App(object):
def __init__(self):
self.tree = None
self._setup_widgets()
def _setup_widgets(self):
butts = tkinter.Button(text = "add line", state="disabled")
butts.grid()
def main():
root = tkinter.Tk()
app = App()
root.mainloop()
if __name__ == "__main__":
main()
Actually issues in one of Ubuntu machine is ssh-keygen command was not run properly. I tried running again and navigated into /home/user1/.ssh and able to see id_rsa and id_rsa.pub keys. then tried command ssh-copy-id and it was working fine.
How about dumping the contents of the database, then using grep
?
$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');
The same utility, pg_dump, can include column names in the output. Just change --inserts
to --column-inserts
. That way you can search for specific column names, too. But if I were looking for column names, I'd probably dump the schema instead of the data.
$ pg_dump --data-only --column-inserts -U postgres your-db-name > a.tmp
$ grep country_code a.tmp
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('US', 'United States');
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('GB', 'United Kingdom');
I know this is late, but this is how I normally do it,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");
Gives the Max Count of record in table
select max(len(Description))from Table_Name
Gives Record Having Greater Count
select Description from Table_Name group by Description having max(len(Description)) >27
Hope helps someone.
request.user.get_username()
or request.user.username
, former is preferred.
Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.
P.S. For templates, use {{ user.get_username }}
In my case, I was assigned approx 120kb base64 value to a static constraint string field in a static class. After then this problem occurred. I was tried a lot of solutions but the problem was not solved until I removed this heavy loaded assignment.
My environment: MS VS Community 2017 Version 15.9.16
Create a theme as below.
<!-- Variation on the Light theme that turns off the title -->
<style name="MyTheme" parent="android:style/Theme.Black">
<item name="android:windowNoTitle">true</item>
</style>
Similar to other syntax above but for learning - can you sort by column names?
sort(colnames(test[1:ncol(test)] ))
here is a simple description of all:
You can use
LEFT(column, length)
or
SUBSTRING(column, start index, length)
To produce the same results:
MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");
AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);
byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);
<import resource="classpath*:spring-config.xml" />
This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.
Your code could look more like:
<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
}
if($username !== 'admin')$userError = 'Invalid Username';
if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<style type='text.css'>
@import common.css;
</style>
</head>
<body>
<form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
<label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
<div class='error'><?php echo $userError;?></div>
<label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
<div class='error'><?php echo $passError;?></div>
<input type='submit' value='Home' name='sub' />
</form>
<script type='text/javascript' src='common.js'></script>
</body>
</html>
From the JDK source:
static <T> Function<T, T> identity() {
return t -> t;
}
So, no, as long as it is syntactically correct.
ToggleImageButton
which implements Checkable
interface and supports OnCheckedChangeListener
and android:checked
xml attribute:
public class ToggleImageButton extends ImageButton implements Checkable {
private OnCheckedChangeListener onCheckedChangeListener;
public ToggleImageButton(Context context) {
super(context);
}
public ToggleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
setChecked(attrs);
}
public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChecked(attrs);
}
private void setChecked(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
a.recycle();
}
@Override
public boolean isChecked() {
return isSelected();
}
@Override
public void setChecked(boolean checked) {
setSelected(checked);
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checked);
}
}
@Override
public void toggle() {
setChecked(!isChecked());
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
}
}
res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleImageButton">
<attr name="android:checked" />
</declare-styleable>
</resources>
Best way to avoid OOM during Bitmap creation,
http://developer.android.com/training/displaying-bitmaps/index.html
I have a Motorola Razr and I was having trouble identifying my device. What I did was:
1 - From the command prompt (as an administrator) -> adb kill-servers
2 - Downloaded Motorola Device Manager here -> https://motorola-global-portal.custhelp.com/app/answers/detail/a_id/88481
3 - I waited until the installation was complete.
4 - From the command prompt (as an administrator) -> adb devices
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:
Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream
Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream
Fix below helped me.
In Dockerfile for nginx container add line:
RUN usermod -u 1000 www-data
In Dockerfile for php-fpm container add line:
RUN usermod -u 1000 www-data
Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.
With your own Code and a Slight Change withou jQuery,
function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
console.log(httpGet(url,key));
}
function httpGet(url,key){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send(null);
return xmlHttp.responseText;
}
Thank You
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
You could escape the % with another % so %%20
This is a similar relevant question Python string formatting when string contains "%s" without escaping
Sweet and simple:
Be aware that there is org.codehaus.jackson.annotate.JsonProperty
in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty
in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.
You May use set
keyword for set the path
set path=%path%;c:/wamp/bin/php/php5.3.0
if all the path are set in path variables
If you want to see all path list. you can use
set %path%
you need to append your php path behind this path.
This is how you can set environment variable.
I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.
One can define a function called shuffled
(in the same sense of sort
vs sorted
)
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
Swift3, ios 10
To globally assign the color, in AppDelegate didFinishLaunchingWithOptions
:
let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
UINavigationBar.appearance().titleTextAttributes = textAttributes
Swift 4, iOS 11
let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
UINavigationBar.appearance().titleTextAttributes = textAttributes
I have been working on Swagger equivalent documentation library called Springfox
nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer
has been implemented by class WebMvcConfigurationSupport
class which we can directly extend.
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
public class WebConfig extends WebMvcConfigurationSupport { }
And this is how I have used it for setting my resource handling mechanism as follows -
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
A concise solution:
location.search
.slice(1)
.split('&')
.map(p => p.split('='))
.reduce((obj, pair) => {
const [key, value] = pair.map(decodeURIComponent);
obj[key] = value;
return obj;
}, {});
This is a verbatim string, and changes the escaping rules - the only character that is now escaped is ", escaped to "". This is especially useful for file paths and regex:
var path = @"c:\some\location";
var tsql = @"SELECT *
FROM FOO
WHERE Bar = 1";
var escaped = @"a "" b";
etc
And for those that are migrating to iOS 8, here is a class extension for Swift:
extension UILabel {
func autoresize() {
if let textNSString: NSString = self.text {
let rect = textNSString.boundingRectWithSize(CGSizeMake(self.frame.size.width, CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: self.font],
context: nil)
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, rect.height)
}
}
}
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:
System.out.println("char " + ch + " has the following value : " + (int) ch);
Here is what I would recommend.
It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.
The idea is that we read the input in large-ish chunks (READALL_CHUNK
), dynamically reallocating the buffer as we need it. We only use realloc()
, fread()
, ferror()
, and free()
:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
/* Size of each input chunk to be
read and allocate for. */
#ifndef READALL_CHUNK
#define READALL_CHUNK 262144
#endif
#define READALL_OK 0 /* Success */
#define READALL_INVALID -1 /* Invalid parameters */
#define READALL_ERROR -2 /* Stream error */
#define READALL_TOOMUCH -3 /* Too much input */
#define READALL_NOMEM -4 /* Out of memory */
/* This function returns one of the READALL_ constants above.
If the return value is zero == READALL_OK, then:
(*dataptr) points to a dynamically allocated buffer, with
(*sizeptr) chars read from the file.
The buffer is allocated for one extra char, which is NUL,
and automatically appended after the data.
Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
char *data = NULL, *temp;
size_t size = 0;
size_t used = 0;
size_t n;
/* None of the parameters can be NULL. */
if (in == NULL || dataptr == NULL || sizeptr == NULL)
return READALL_INVALID;
/* A read error already occurred? */
if (ferror(in))
return READALL_ERROR;
while (1) {
if (used + READALL_CHUNK + 1 > size) {
size = used + READALL_CHUNK + 1;
/* Overflow check. Some ANSI C compilers
may optimize this away, though. */
if (size <= used) {
free(data);
return READALL_TOOMUCH;
}
temp = realloc(data, size);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
}
n = fread(data + used, 1, READALL_CHUNK, in);
if (n == 0)
break;
used += n;
}
if (ferror(in)) {
free(data);
return READALL_ERROR;
}
temp = realloc(data, used + 1);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
data[used] = '\0';
*dataptr = data;
*sizeptr = used;
return READALL_OK;
}
Above, I've used a constant chunk size, READALL_CHUNK
== 262144 (256*1024
). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.
The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.
For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK
, perhaps #define READALL_CHUNK 2097152
(2 MiB).
Because the definition of READALL_CHUNK
is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152
command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.
Language[] items = new Language[]{new Language("English", "En"),
new Language("Italian", "It")};
languagesCombo.ValueMember = "Alias";
languagesCombo.DisplayMember = "FullName";
languagesCombo.DataSource = items.ToList();
languagesCombo.DropDownStyle = ComboBoxStyle.DropDownList;
class Language
{
public string FullName { get; set; }
public string Alias { get; set; }
public Language(string fullName, string alias)
{
this.FullName = fullName;
this.Alias = alias;
}
}
By making your drop down box "read-only" I am assuming you want to prevent user's typing in other options as opposed to being fully read-only where users cannot select a value??
If you wanted it to be fully read-only you could set the enabled property to be false.
I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.
The issue here is that the error detail is logged but not reported, so check the logs.
Given that the only logical difference between the handlers is the value of the button clicked, you can use the this
keyword to refer to the element which raised the event and get the val()
from that. Try this:
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/pages/test/",
data: {
id: $(this).val(), // < note use of 'this' here
access_token: $("#access_token").val()
},
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
});
For IDLE, select the lines, then open the "Format" menu. (Between "Edit" and "Run" if you're having trouble finding it.) This will also give you the keyboard shortcut, for me it turned out that dedent shortcut was "Ctrl+["
function GetCellValues() {
var table = document.getElementById('mytable');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].innerHTML);
}
}
}
I want to complete the answer from tchester.
(1) Enable the xp_cmdshell procedure:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database
(3) Grant EXEC permission on the xp_cmdshell stored procedure:
GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]
(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
-- Don't include square brackets around Domain\TestUser.
(5) Grant control server permission to user
USE master;
GRANT CONTROL SERVER TO [Domain\TestUser]
GO
Assuming that you really do want an array and not a std::vector, the "C++ way" would be this
#include <algorithm>
int* array = new int[n]; // Assuming "n" is a pre-existing variable
std::fill_n(array, n, 0);
But be aware that under the hood this is still actually just a loop that assigns each element to 0 (there's really not another way to do it, barring a special architecture with hardware-level support).
Neither is more correct, so take your pick. The empty return;
statement is provided to allow a return in a void
function from somewhere other than the end. No other reason I believe.
Blowfish is not a hashing algorithm. It's an encryption algorithm. What that means is that you can encrypt something using blowfish, and then later on you can decrypt it back to plain text.
SHA512 is a hashing algorithm. That means that (in theory) once you hash the input you can't get the original input back again.
They're 2 different things, designed to be used for different tasks. There is no 'correct' answer to "is blowfish better than SHA512?" You might as well ask "are apples better than kangaroos?"
If you want to read some more on the topic here's some links:
public static void main(String[] args) {
List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
AtomicBoolean yes = new AtomicBoolean(true);
list.stream().takeWhile(value -> yes.get()).forEach(value -> {
System.out.println("prior cond" + value);
if (value.equals("two")) {
System.out.println(value);
yes.set(false);
}
});
//System.out.println("Hello World");
}
The previous answers are pretty confusing. You don't need a react-state to solve this, nor any special external lib. It can be achieved with pure css/sass:
The style:
.hover {
position: relative;
&:hover &__no-hover {
opacity: 0;
}
&:hover &__hover {
opacity: 1;
}
&__hover {
position: absolute;
top: 0;
opacity: 0;
}
&__no-hover {
opacity: 1;
}
}
The React-Component
A simple Hover
Pure-Rendering-Function:
const Hover = ({ onHover, children }) => (
<div className="hover">
<div className="hover__no-hover">{children}</div>
<div className="hover__hover">{onHover}</div>
</div>
)
Usage
Then use it like this:
<Hover onHover={<div> Show this on hover </div>}>
<div> Show on no hover </div>
</Hover>
One of the main reason for this error is due to permission not granted to all users. so remove this error, follow the following steps :
1) Go to the C:/Programme Files/Apache Software Foundation/Tomcat 7.0
2) Right click on the Tomcat 7.0 folder and click on properties.
3) go to Security Tab.
4) Select the User and click on Edit... button
5) Grant all the permission to the user and click on apply and ok.
Refresh the system and now try. I hope it will work
It's been a while since I posted this question, but considering the views this still seems to get, here's another solution I've come upon during these last few months:
$scope.safeApply = function( fn ) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn) {
fn();
}
} else {
this.$apply(fn);
}
};
The above code basically creates a function called safeApply
that calles the $apply
function (as stated in Arun's answer) if and only Angular currently isn't going through the $digest
stage. On the other hand, if Angular is currently digesting things, it will just execute the function as it is, since that will be enough to signal to Angular to make the changes.
Numerous errors occur when trying to use the $apply
function while AngularJs is currently in its $digest
stage. The safeApply
code above is a safe wrapper to prevent such errors.
(note: I personally like to chuck in safeApply
as a function of $rootScope
for convenience purposes)
Example:
function change() {
alert("a");
var scope = angular.element($("#outer")).scope();
scope.safeApply(function(){
scope.msg = 'Superhero';
})
}
You can also use time
library:
import time
start = time.time()
# your code
# end
print(f'Time: {time.time() - start}')
I too found Python lacking when it comes to reading and writing binary files, so I wrote a small module (for Python 3.6+).
With binaryfile you'd do something like this (I'm guessing, since I don't know Fortran):
import binaryfile
def particle_file(f):
f.array('group_ids') # Declare group_ids to be an array (so we can use it in a loop)
f.skip(4) # Bytes 1-4
num_particles = f.count('num_particles', 'group_ids', 4) # Bytes 5-8
f.int('num_groups', 4) # Bytes 9-12
f.skip(8) # Bytes 13-20
for i in range(num_particles):
f.struct('group_ids', '>f') # 4 bytes x num_particles
f.skip(4)
with open('myfile.bin', 'rb') as fh:
result = binaryfile.read(fh, particle_file)
print(result)
Which produces an output like this:
{
'group_ids': [(1.0,), (0.0,), (2.0,), (0.0,), (1.0,)],
'__skipped': [b'\x00\x00\x00\x08', b'\x00\x00\x00\x08\x00\x00\x00\x14', b'\x00\x00\x00\x14'],
'num_particles': 5,
'num_groups': 3
}
I used skip() to skip the additional data Fortran adds, but you may want to add a utility to handle Fortran records properly instead. If you do, a pull request would be welcome.
Try this in cmd:
cd address_of_sumatrapdf.exe_file && sumatrapdf.exe
Where you should put the address of your .exe file instead of adress_of_sumatrapdf.exe_file.
How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.
Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:
git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch
I was facing "java.lang.OutOfMemoryError: Java heap space" error while building my project using maven install command.
I was able to get rid of it by changing maven runner settings.
Settings
| Build, Execution, Deployment
| Build Tools
| Maven
| Runner
| VM options
to -Xmx512m
As it allows to install more than one version of java, I had install many 3 versions unknowingly but it was point to latest version "11.0.2"
I could able to solve this issue with below steps to move to "1.8"
$java -version
openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
cd /Library/Java/JavaVirtualMachines
ls
jdk1.8.0_201.jdk jdk1.8.0_202.jdk openjdk-11.0.2.jdk
sudo rm -rf openjdk-11.0.2.jdk
sudo rm -rf jdk1.8.0_201.jdk
ls
jdk1.8.0_202.jdk
java -version
java version "1.8.0_202-ea" Java(TM) SE Runtime Environment (build 1.8.0_202-ea-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b03, mixed mode)
If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:
'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long
'***App Window Constants***
Public Const WIN_NORMAL = 1 'Open Normal
Public Const WIN_MAX = 3 'Open Maximized
Public Const WIN_MIN = 2 'Open Minimized
'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&
'***************Usage Examples***********************
'Open a folder: ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app: ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL: ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
' ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
' ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************
Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
'First try ShellExecute
lRet = apiShellExecute(hWndAccessApp, vbNullString, _
stFile, vbNullString, vbNullString, lShowHow)
If lRet > ERROR_SUCCESS Then
stRet = vbNullString
lRet = -1
Else
Select Case lRet
Case ERROR_NO_ASSOC:
'Try the OpenWith dialog
varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
& stFile, WIN_NORMAL)
lRet = (varTaskID <> 0)
Case ERROR_OUT_OF_MEM:
stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
Case ERROR_FILE_NOT_FOUND:
stRet = "Error: File not found. Couldn't Execute!"
Case ERROR_PATH_NOT_FOUND:
stRet = "Error: Path not found. Couldn't Execute!"
Case ERROR_BAD_FORMAT:
stRet = "Error: Bad File Format. Couldn't Execute!"
Case Else:
End Select
End If
fHandleFile = lRet & _
IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********
Just put this into a separate module and call fHandleFile() with the right parameters.
found this in 2020 and solution solved the issue with OMZ https://stackoverflow.com/a/13018777/13222154
...
? ~ cd $ZSH
? .oh-my-zsh (master) ? git remote -v
origin https://github.com/ohmyzsh/ohmyzsh.git (fetch)
origin https://github.com/ohmyzsh/ohmyzsh.git (push)
? .oh-my-zsh (master) ? date ; omz update
Wed Sep 30 16:16:31 CDT 2020
Updating Oh My Zsh
fatal: Unable to find remote helper for 'https'
There was an error updating. Try again later?
omz::update: restarting the zsh session...
...
ln "$execdir/git-remote-http" "$execdir/$p" 2>/dev/null || \
ln -s "git-remote-http" "$execdir/$p" 2>/dev/null || \
cp "$execdir/git-remote-http" "$execdir/$p" || exit; \
done && \
./check_bindir "z$bindir" "z$execdir" "$bindir/git-add"
? git-2.9.5
? git-2.9.5
? git-2.9.5
? git-2.9.5 omz update
Updating Oh My Zsh
remote: Enumerating objects: 296, done.
remote: Counting objects: 100% (296/296), done.
remote: Compressing objects: 100% (115/115), done.
remote: Total 221 (delta 146), reused 179 (delta 105), pack-reused 0
Receiving objects: 100% (221/221), 42.89 KiB | 0 bytes/s, done.
Resolving deltas: 100% (146/146), completed with 52 local objects.
From https://github.com/ohmyzsh/ohmyzsh
* branch master -> FETCH_HEAD
7deda85..f776af2 master -> origin/master
Created autostash: 273f6e9
You've encountered a local time discontinuity:
When local standard time was about to reach Sunday, 1. January 1928, 00:00:00 clocks were turned backward 0:05:52 hours to Saturday, 31. December 1927, 23:54:08 local standard time instead
This is not particularly strange and has happened pretty much everywhere at one time or another as timezones were switched or changed due to political or administrative actions.
I think the better library to handle gif files is this one: by koral
Used it and i'm successful and this library is dedicated to GIF'S; but where as the picasso and glide are general purpose image framework; so i think the developers of this library have entirely concentrated on gif files
use
$("#mySelectBox option:selected");
to test if its a particular option myoption
:
if($("#mySelectBox option:selected").text() == myoption){
//...
}
alternative would be javascript and forwarding via the onclick event
<div onclick="window.location.href='somewhere...';">...</div>
Scroll down on that page and you'll see:
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
That's the SQLEXPRWT_x64_ENU.exe
download.... (WT = with tools)
Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.
That's the SQLEXPRADV_x64_ENU.exe
download ... (ADV = Advanced Services)
The SQLEXPR_x64_ENU.exe
file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.
Follow the steps mentioned for using support ActionBar in Android Studio(0.4.2) :
Download the Android Support Repository from Android SDK Manager, SDK Manager icon will be available on Android Studio tool bar (or Tools -> Android -> SDK Manager
).
After download you will find your Support repository here
$SDK_DIR\extras\android\m2repository\com\android\support\appcompat-v7
Open your main module's build.gradle file and add following dependency for using action bar in lower API level
dependencies {
compile 'com.android.support:appcompat-v7:+'
}
Sync your project with gradle using the tiny Gradle icon available in toolbar (or Tools -> Android -> Sync Project With Gradle Files
).
There is some issue going on with Android Studio 0.4.2 so check this as well if you face any issue while importing classes in code.
Import Google Play Services library in Android Studio
If Required follow the steps as well :
This is bug in Android Studio 0.4.2 and fixed for Android Studio 0.4.3 release.
*IntelliJ 13 * (its paid for) We found you have to have the cursor in the actual class before ctrl+Shift+T worked.
Which seems a bit restrictive if its the only way to generate a test class. Although in retrospect it would force developers to create a test class when they write a functional class.
For the sake of completeness, http://github.com/alex/pyvcs/ is an abstraction layer for all dvcs's. It uses dulwich, but provides interop with the other dvcs's.
You may want to use the appendTo
function (which adds to the end of the element):
$("#source").appendTo("#destination");
Alternatively you could use the prependTo
function (which adds to the beginning of the element):
$("#source").prependTo("#destination");
Example:
$("#appendTo").click(function() {_x000D_
$("#moveMeIntoMain").appendTo($("#main"));_x000D_
});_x000D_
$("#prependTo").click(function() {_x000D_
$("#moveMeIntoMain").prependTo($("#main"));_x000D_
});
_x000D_
#main {_x000D_
border: 2px solid blue;_x000D_
min-height: 100px;_x000D_
}_x000D_
_x000D_
.moveMeIntoMain {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="main">main</div>_x000D_
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>_x000D_
_x000D_
<button id="appendTo">appendTo main</button>_x000D_
<button id="prependTo">prependTo main</button>
_x000D_
As of Ansible 2.0 there seems to be an option called strategy
on a playbook. When setting the strategy to free
, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.
It looks something like this (taken from the above link):
- hosts: all
strategy: free
tasks:
...
Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.
EDIT:
It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.
This includes specifying async
and poll
on a task. The following is taken from the 2nd link I mentioned:
- name: simulate long running op, allow to run for 45 sec, fire and forget
command: /bin/sleep 15
async: 45
poll: 0
I guess you can specify longer async
times if your task is lengthy. You can probably define your three concurrent task this way.
If you want to see three windows along with Log
Then go to windows on NetBeans
then output
and click NetBeans->windows->output
.
Next go to service next to you project select server right click on it select server log and server output NetBeans->service(next to you project)->server->View server log
and view service output.
In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.
char * returnArray(char *arr, int size) {
char *new_arr = malloc(sizeof(char) * size);
for(int i = 0; i < size; ++i) {
new_arr[i] = arr[i];
}
return new_arr;
}
int main() {
char arr[7]= {1,0,0,0,0,1,1};
char *new_arr = returnArray(arr, 7);
// don't forget to free the memory after you're done with the array
free(new_arr);
}
Using Ubuntu 12.04 it appears to work fine for me:
jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
python-psycopg2-doc
The following NEW packages will be installed
python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.
What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update
to make sure your repo. is up to date.
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
A simple, robust and elegant download manager supporting simultaneous downloads with closure syntax for progress and completion tracking. Written in Swift with Here
And Use like it
func downloadGIF(url: String) {
let filename = url
let range: Range<String.Index> = filename.range(of:"media/")!
let lastrange: Range<String.Index> = filename.range(of:"/200w_d")!
let finalPath = String(filename[range.lowerBound..<lastrange.lowerBound])
filename[range.lowerBound..<lastrange.lowerBound]
let replaceFirstWords = finalPath.replace(string: "media/", replacement: "SocialStatus_GIF_")
let destinationUrl = "\(replaceFirstWords).gif"
let request = URLRequest(url: URL(string: imageData.bg_image)!)
viewProgress.isHidden = false
self.btnDownload.isHidden = true
setSharingButtonFalse()
let downloadKey = self.downloadManager.downloadFile(withRequest: request,
withName: destinationUrl,
shouldDownloadInBackground: true,
onProgress: { [weak self] (progress) in
self?.viewProgress.progress = CGFloat(progress)
let val = progress * 100
print("val 1 == \(val)")
DispatchQueue.main.async {
self?.viewProgress.setProgressText("\(Int(val))")
}
}) { [weak self] (error, url) in
if let error = error {
print("Error = \(error as NSError)")
self!.isDownloaded = false
self!.viewProgress.isHidden = true
self!.setSharingButtonTrue()
self?.viewProgress.setProgressText("\(0)")
print("handle error since couldn't save GIF")
} else {
if let url = url {
self!.isDownloaded = true
self!.saveGIFDownloaded()
self!.viewProgress.isHidden = true
self!.setSharingButtonTrue()
self!.createAlbum()
self!.saveGIF(url: url.absoluteURL)
}
}
}
}
Here is the difference between basename(__FILE__, ".php")
and basename($_SERVER['REQUEST_URI'], ".php")
.
basename(__FILE__, ".php")
shows the name of the file where this code is included - It means that if you include this code in header.php and current page is index.php, it will return header not index.
basename($_SERVER["REQUEST_URI"], ".php")
- If you use include this code in header.php and current page is index.php, it will return index not header.
This works:
$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);
git init
git add .
git commit -m "Initial commit"
After this, make a new GitHub repository and follow on-screen instructions.
How do you change your cursor to the finger (like for clicking on links) instead of the regular pointer?
This is very simple to achieve using the CSS property cursor
, no jQuery
needed.
You can read more about in: CSS cursor property
and cursor - CSS | MDN
.default {_x000D_
cursor: default;_x000D_
}_x000D_
.pointer {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<a class="default" href="#">default</a>_x000D_
_x000D_
<a class="pointer" href="#">pointer</a>
_x000D_
Windows: Mostly C and C++, some C#
I have been doing PHP for my project, and I can say that the following code works for me. You should try it.
echo '<input type = "text" value = '.$idtest.'>';
According to reactjs.org, componentWillMount will not be supported in the future. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount
There is no need to use componentWillMount.
If you want to do something before the component mounted, just do it in the constructor().
If you want to do network requests, do not do it in componentWillMount. It is because doing this will lead to unexpected bugs.
Network requests can be done in componentDidMount.
Hope it helps.
updated on 08/03/2019
The reason why you ask for componentWillMount is probably because you want to initialize the state before renders.
Just do it in useState.
const helloWorld=()=>{
const [value,setValue]=useState(0) //initialize your state here
return <p>{value}</p>
}
export default helloWorld;
or maybe You want to run a function in componentWillMount, for example, if your original code looks like this:
componentWillMount(){
console.log('componentWillMount')
}
with hook, all you need to do is to remove the lifecycle method:
const hookComponent=()=>{
console.log('componentWillMount')
return <p>you have transfered componeWillMount from class component into hook </p>
}
I just want to add something to the first answer about useEffect.
useEffect(()=>{})
useEffect runs on every render, it is a combination of componentDidUpdate, componentDidMount and ComponentWillUnmount.
useEffect(()=>{},[])
If we add an empty array in useEffect it runs just when the component mounted. It is because useEffect will compare the array you passed to it. So it does not have to be an empty array.It can be array that is not changing. For example, it can be [1,2,3] or ['1,2']. useEffect still only runs when component mounted.
It depends on you whether you want it to run just once or runs after every render. It is not dangerous if you forgot to add an array as long as you know what you are doing.
I created a sample for hook. Please check it out.
https://codesandbox.io/s/kw6xj153wr
updated on 21/08/2019
It has been a while since I wrote the above answer. There is something that I think you need to pay attention to. When you use
useEffect(()=>{},[])
When react compares the values you passed to the array [], it uses Object.is()
to compare.
If you pass an object to it, such as
useEffect(()=>{},[{name:'Tom'}])
This is exactly the same as:
useEffect(()=>{})
It will re-render every time because when Object.is()
compares an object, it compares its reference, not the value itself. It is the same as why {}==={} returns false because their references are different.
If you still want to compare the object itself not the reference, you can do something like this:
useEffect(()=>{},[JSON.stringify({name:'Tom'})])
Natively that is not possible, yet. See also this feature request.
So far you need to do that in your containers CMD
to wait until all required services are there.
In the Dockerfile
s CMD
you could refer to your own start script that wraps starting up your container service. Before you start it, you wait for a depending one like:
Dockerfile
FROM python:2-onbuild
RUN ["pip", "install", "pika"]
ADD start.sh /start.sh
CMD ["/start.sh"]
start.sh
#!/bin/bash
while ! nc -z rabbitmq 5672; do sleep 3; done
python rabbit.py
Probably you need to install netcat in your Dockerfile
as well. I do not know what is pre-installed on the python image.
There are a few tools out there that provide easy to use waiting logic, for simple tcp port checks:
For more complex waits:
session_start(); //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id']; //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);
//print_r($_SESSION['student']);
<table class="table"> //html part
<tr>
<th>Name</th>
<th>City</th>
</tr>
<tr>
<?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
echo '<td>'.$_SESSION['student'][$i].'</td>';
} ?>
</tr>
</table>
Direct use of .reduce
can be hard to read, so I'd recommend creating a function that generates the reducer for you:
function mapfilter(mapper) {
return (acc, val) => {
const mapped = mapper(val);
if (mapped !== false)
acc.push(mapped);
return acc;
};
}
Use it like so:
const words = "Map and filter an array #javascript #arrays";
const tags = words.split(' ')
.reduce(mapfilter(word => word.startsWith('#') && word.slice(1)), []);
console.log(tags); // ['javascript', 'arrays'];
It's a very interesting question.
You can use both of them, there's not any strict rule about this subject, but using URI path variables has some advantages:
But if you use path variables, all of this services can cache your GET requests.
It gives the user more information about the structure of the data.
But if your data doesn't have any hierarchy relation you can still use Path variables, using comma or semi-colon:
/City/longitude,latitude
As a rule, use comma when the ordering of the parameters matter, use semi-colon when the ordering doesn't matter:
/IconGenerator/red;blue;green
Apart of those reasons, there are some cases when it's very common to use query string variables:
http:// www.google.com/search?q=rest
To sum up, there's not any strong reason to use one of this methods but whenever you can, use URI variables.
I use easy_install with Apple's Python, and it works like a charm.
Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.
Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.
In some cases first your need to Release, then Remove and Re-add via Virtual Media Manager
Using ggplot
and a little dplyr
for data manipulation:
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))
library(ggplot2)
library(dplyr)
df.summary <- df %>% group_by(x) %>%
summarize(ymin = min(y),
ymax = max(y),
ymean = mean(y))
ggplot(df.summary, aes(x = x, y = ymean)) +
geom_point(size = 2) +
geom_errorbar(aes(ymin = ymin, ymax = ymax))
If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by
call (e.g., group_by(x, file)
if file
is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file)
.
You could call:
getContentPane().setBackground(Color.black);
Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call
setBackground(Color.black);
on the JPanel to set the background color.
Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():
Thread t = new Thread(new Runnable(){
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}});
t.start();
// Sleep a second, and then interrupt
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
t.interrupt();
There's no need, just use fadeToggle()
on the element:
$('#testElement').fadeToggle('fast');
To find the distance between 2 points, you need to find the length of the hypotenuse in a right angle triangle with a width and height equal to the vertical and horizontal distance:
Math.hypot(endX - startX, endY - startY)
You can use "group by" + "orderby". See LINQ 101 for details
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
In response to this post (now deleted):
If you have a list of some custom objects then you need to use custom comparer or group by specific property.
Also query can't display result. Show us complete code to get a better help.
Based on your latest update:
You have this line of code:
group xx by xx into g
Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
CHAR
is a fixed-length data type that uses as much space as possible. So a:= a||'one ';
will require more space than is available. Your problem can be reduced to the following example:
declare
v_foo char(50);
begin
v_foo := 'A';
dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
-- next line will raise:
-- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
v_foo := v_foo || 'B';
dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));
end;
/
Never use char
. For rationale check the following question (read also the links):
Actually, to query the team_name
, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.
from urllib2 import urlopen
import json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)
for i in json_obj['team']:
print i['team_name']
in my case, the SFTP server will reject your SSH connection.
SOA is acronym for Service Oriented Architecture.
SOA is designing and writing software applications in such a way that distinct software modules can be integrated seamlessly with high degree of re-usability.
Most of the people restrict SOA as writing client/server software-web-services. But it is too small context of SOA. SOA is much larger than that and over the past few years web-services have been primary medium of communcation which is probably the reason why people think of SOA as web-services in general restricting the boundaries and meaning of SOA.
You can think of writing a database-access module which is so independent that it can work on its own without any dependencies. This module can expose classes which can be used by any host-software that needs database access. There's no start-up configuration in host-application. Whatever is needed or required is communicated through classes exposes by database-access module. We can call these classes as services and consider the module as service-enabled.
Practicing SOA gives high degree of re-usability by enforcing DRY [Don't repeat your self] which results into highly maintainable software. Maintainability is the first thing any software architecture thinks of - SOA gives you that.
Set up a batch file which you can invoke. Pass the path the batch file, and have the batch file set the environment variable and then invoke NUnit.
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'your-icon.png'
});
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
Deleting/commenting
- (void)viewWillAppear:(BOOL)animated {[super viewWillAppear:YES];}
function solved the problem for me.
XCode (11.3.1)
John's answer won't produce .txt files as the OP wants. Use:
split -b=1M -d file.txt file --additional-suffix=.txt
System.exit() terminates the JVM. Nothing after System.exit() is executed. Return is generally used for exiting a method. If the return type is void, then you could use return; But I don't think is a good practice to do it in the main method. You don't have to do anything for terminate a program, unless infinite loop or some strange other execution flows.
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
I'd suggest doing this with a combination of
overflow-y: hidden;
scrolling="no"
(for HTML4)seamless="seamless"
(for HTML5)* The seamless
attribute has been removed from the standard, and no browsers support it.
.foo {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
class="foo" _x000D_
scrolling="no" >_x000D_
</iframe>
_x000D_
Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:
var date = new Date(); //Current timestamp_x000D_
date = date.toGMTString(); _x000D_
//Based on the time zone where the date was created_x000D_
console.log(date);_x000D_
_x000D_
/*based on the comment getTimezoneOffset returns an offset based _x000D_
on the date it is called on, and the time zone of the computer the code is_x000D_
running on. It does not supply the offset passed in when constructing a _x000D_
date from a string. */_x000D_
_x000D_
date = new Date(date); //will convert to present timestamp offset_x000D_
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000)); _x000D_
console.log(date);
_x000D_
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
You can use the first method:
$('li').first()
btw I agree with Nick Craver -- use document.getElementById()...
As @ganaraj mentioned AngularJS has dependency injection at its core. When building toy seed applications with and without RequireJS, I personally found RequireJS was probably overkill for most use cases.
That doesn't mean RequireJS is not useful for it's script loading capabilities and keeping your codebase clean during development. Combining the r.js optimizer (https://github.com/jrburke/r.js) with almond (https://github.com/jrburke/almond) can create a very slim script loading story. However since its dependency management features are not as important with angular at the core of your application, you can also evaluate other client side (HeadJS, LABjs, ...) or even server side (MVC4 Bundler, ...) script loading solutions for your particular application.
Closest you'd get to a struct is an object with all members public.
class MyStruct {
public $foo;
public $bar;
}
$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';
I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input : Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') , just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.
If you return a string, you'll get a string.
Alright, I had the same problem, and none of these answers worked for me (I'm running Windows 8). I tried running tools/android.bat
and noticed I got some errors there. I investigated further and it seems there is something wrong in the code that finds your Java path.
This is how you fix it:
tools/android.bat
in your favorite text editorSearch for this piece of code:
set java_exe=
call lib\find_java.bat
if not defined java_exe goto :EOF
Replace it with this:
set java_exe=D:\Program Files\Java\jdk1.7.0_07\bin\java.exe
where the path is the path to your Java exe.
Run android.bat
(in my case I had to specify the path to java_exe
in step 3 with no quotes to make it work.)
It says right there in the output of git status
:
# (use "git add/rm <file>..." to update what will be committed)
so just do:
git rm <filename>
My fix using Android Studio 3.0.0 on Windows 10 is to remove entirely any jvm args from the gradle.properties file.
I am using the Android gradle wrapper 3.0.1 with gradle version 4.1. No gradlew commands were working, but a warning says that it's trying to ignore any jvm memory args as they were removed in 8 (which I assume is Java 8).
Firebase Cloud Messaging has a server-side APIs that you can call to send messages. See https://firebase.google.com/docs/cloud-messaging/server.
Sending a message can be as simple as using curl
to call a HTTP end-point. See https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"
Try to Re-Import the project from the Maven Projects panel in IntelliJ IDEA. It should download and configure all the dependencies defined in your pom.xml
automatically.
If download doesn't work from IDEA for some reason, try mvn install
from the command line and see if the dependencies can be fetched.
Of course all the required dependencies and any custom repositories must be defined directly in the pom.xml
file.
If you are using Oracle 12c, use:
FETCH NEXT N ROWS ONLY
SELECT DISTINCT
APP_ID,
NAME,
STORAGE_GB,
HISTORY_CREATED,
TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE
FROM HISTORY WHERE
STORAGE_GB IS NOT NULL AND
APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
ORDER BY STORAGE_GB DESC
FETCH NEXT 10 ROWS ONLY
More info: http://docs.oracle.com/javadb/10.5.3.0/ref/rrefsqljoffsetfetch.html
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:
Now I got the solution to the problem which I have faced: The TFS remembered the prior password when I got logged in by using my mobile VPN.
Solution:
Resetting the account that I used to connect using VPN
Try to add auth method explicitly as below, because sometimes it is required:
session.setConfig("PreferredAuthentications", "password");
Don't use "new Date()", because it takes the input date string as local time:
new Date('11/08/2010').getTime()-new Date('11/07/2010').getTime(); //90000000
new Date('11/07/2010').getTime()-new Date('11/06/2010').getTime(); //86400000
we should use "NewDate()", it takes the input as GMT time:
function NewDate(str)
{str=str.split('-');
var date=new Date();
date.setUTCFullYear(str[0], str[1]-1, str[2]);
date.setUTCHours(0, 0, 0, 0);
return date;
}
NewDate('2010-11-07').toGMTString();
NewDate('2010-11-08').toGMTString();
Credit to EM0 for https://stackoverflow.com/a/17600012/4151626
The other solutions (including EM0's) still deadlocked for my application, due to internal timeouts and the use of both StandardOutput and StandardError by the spawned application. Here is what worked for me:
Process p = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = exe,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
p.Start();
string cv_error = null;
Thread et = new Thread(() => { cv_error = p.StandardError.ReadToEnd(); });
et.Start();
string cv_out = null;
Thread ot = new Thread(() => { cv_out = p.StandardOutput.ReadToEnd(); });
ot.Start();
p.WaitForExit();
ot.Join();
et.Join();
Edit: added initialization of StartInfo to code sample
You can't use php code client-side. You need to use javascript.
<input type="button" value="Home" class="homebutton" id="btnHome"
onClick="document.location.href='some/page'" />
However, you really shouldn't be using inline js (like onclick here). Study about this here: https://www.google.com/search?q=Why+is+inline+js+bad%3F
Here's a clean way of doing this: Live demo (click).
Markup:
<button id="myBtn">Redirect</button>
JavaScript:
var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
document.location.href = 'some/page';
});
If you need to write in the location with php:
<button id="myBtn">Redirect</button>
<script>
var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
document.location.href = '<?php echo $page; ?>';
});
</script>
Simplest solution is probably to use tr
$ cat -A input
^I Name, ^IOrder $
Trim, working $
cat,cat1^I
$ tr -d '[:blank:]' < input | cat -A
Name,Order$
Trim,working$
cat,cat1
I am able to use this feature on my machine using MS Access 2007.
For what its worth, I'm using Access 2007 SP1
I haven't tested your code, just tried to help you understand how it operates in comment;
WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID
The simplest example of a recursive CTE
I can think of to illustrate its operation is;
;WITH Numbers AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM Numbers
WHERE n+1 <= 10
)
SELECT n
FROM Numbers
Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.
A1:
In this case, N
is not a variable. N
is an alias. It is the equivalent of SELECT 1 AS N
. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE
in T-SQL
. I've included the analog of a simple CTE
in Excel
to try and illustrate in a more familiar way what is happening.
-- Outside
;WITH CTE (MyColName) AS
(
SELECT 1
)
-- Inside
;WITH CTE AS
(
SELECT 1 AS MyColName
-- Or
SELECT MyColName = 1
-- Etc...
)
Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager
A2:
Does this code answer your question?
--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS
(
SELECT 1, 'Keith', NULL UNION ALL
SELECT 2, 'Josh', 1 UNION ALL
SELECT 3, 'Robin', 1 UNION ALL
SELECT 4, 'Raja', 2 UNION ALL
SELECT 5, 'Tridip', NULL UNION ALL
SELECT 6, 'Arijit', 5 UNION ALL
SELECT 7, 'Amit', 5 UNION ALL
SELECT 8, 'Dev', 6
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
-- Anchor
SELECT ID
,Name
,MgrID
,nLevel = 1
,Family = ROW_NUMBER() OVER (ORDER BY Name)
FROM Employee
WHERE MgrID IS NULL
UNION ALL
-- Recursive query
SELECT E.ID
,E.Name
,E.MgrID
,H.nLevel+1
,Family
FROM Employee E
JOIN Hierarchy H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel
SELECT ID,space(nLevel+
(CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
)+Name
FROM Hierarchy
ORDER BY Family, nLevel
hist
can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar
. Example:
Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)
or if you want a one-liner:
bar(hist(Y) ./ sum(hist(Y)))
Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz
as proposed by R. M.
On Ubuntu/Debian, you can install it with apt-get install python-simplejson
As Jonathan Leffler points out above, the macOS_SDK_headers.pkg file is no longer there in Xcode 10.1.
What worked for me was to do brew upgrade
and the updates of gcc and/or whatever else homebrew did behind the scenes resolved the path problems.
You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
This works for me:
convert original.png -fuzz 10% -transparent white transparent.png
where the smaller the fuzz %, the closer to true white or conversely, the larger the %, the more variation from white is allowed to become transparent
You could try using £
or £
instead of embedding the character directly; if you embed it directly, you're more likely to run into encoding issues in which your editor saves the file is ISO-8859-1 but it's interpreted as UTF-8, or vice versa.
If you want to embed it (or other Unicode characters) directly, make sure you actually save your file as UTF-8, and set the encoding as you did with the Content-Type
header. Make sure when you get the file from the server that the header is present and correct, and that the file hasn't been transcoded by the web server.
It worked for me, but only with ssh key and not with username and password.
After i added the ssh key to sourcetree, i changed the settings under Tools -> Options -> SSH-Client to work with PuTTY/Plink.
I run into trouble after i added the ssh key, because i forgot to restart sourceTree. "this is necessary so that there is an instance of ssh-agent running that SourceTree can talk to with your key loaded." See here: https://answers.atlassian.com/questions/189412/sourcetree-with-gitlab-ssh-not-working
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null
and not for empty strings then you can also use ifnull()
or coalesce(field1, 'empty')
. But that is not suitable for empty strings.
If you want to extract from a
tag then
$('.dep_buttons').text().substr(0,25)
With the mouseover event,
$(this).text($(this).text().substr(0, 25));
The above will extract the text of a tag, then extract again assign it back.
I had this issue for a day until I found the real resolution. Instead of trying to force unmount an smb share that is hung, mount the share with the "soft" option. If a process attempts to connect to the share that is not available it will stop trying after a certain amount of time.
soft Make the mount soft. Fail file system calls after a number of seconds.
mount -t smbfs -o soft //username@server/share /users/username/smb/share
stat /users/username/smb/share/file
stat: /users/username/smb/share/file: stat: Operation timed out
May not be a real answer to your question but it is a solution to the problem
It's a reference to the current object, it's most commonly used in object oriented code.
Example:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
This stores the 'Jack' string as a property of the object created.
I've found the solution.
I used: outline:none;
in the CSS and it seems to have worked. Thanks for the help anyway. :)
Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?
Use dynamic query as below:
String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;
If I want to simply run the above query and get a List what is the best way?
List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){
public String mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getString(1);
}
});
EDIT: To Stop SQL Injection, check for non word characters in the colName as :
Pattern pattern = Pattern.compile("\\W");
if(pattern.matcher(str).find()){
//throw exception as invalid column name
}
You can use inline assembly for the function call. (in this code I assume the arguments are characters).
void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
{
va_list argumentsToPass;
va_start(argumentsToPass, fmt);
char *list = new char[numOfArgs];
for(int n = 0; n < numOfArgs; n++)
list[n] = va_arg(argumentsToPass, char);
va_end(argumentsToPass);
for(int n = numOfArgs - 1; n >= 0; n--)
{
char next;
next = list[n];
__asm push next;
}
__asm push fmt;
__asm call format_string;
fprintf(stdout, fmt);
}
As of .net3.5+ instead of using a Dictionary<IKey, List<IValue>>
you can use a Lookup
from the Linq namespace:
// lookup Order by payment status (1:m)
// would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
IEnumerable<Order> payedOrders = byPayment[false];
From msdn:
A Lookup resembles a Dictionary. The difference is that a Dictionary maps keys to single values, whereas a Lookup maps keys to collections of values.
You can create an instance of a Lookup by calling ToLookup on an object that implements IEnumerable.
You may also want to read this answer to a related question. For more info, consult msdn.
Full example:
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqLookupSpike
{
class Program
{
static void Main(String[] args)
{
// init
var orderList = new List<Order>();
orderList.Add(new Order(1, 1, 2010, true));//(orderId, customerId, year, isPayed)
orderList.Add(new Order(2, 2, 2010, true));
orderList.Add(new Order(3, 1, 2010, true));
orderList.Add(new Order(4, 2, 2011, true));
orderList.Add(new Order(5, 2, 2011, false));
orderList.Add(new Order(6, 1, 2011, true));
orderList.Add(new Order(7, 3, 2012, false));
// lookup Order by its id (1:1, so usual dictionary is ok)
Dictionary<Int32, Order> orders = orderList.ToDictionary(o => o.OrderId, o => o);
// lookup Order by customer (1:n)
// would need something like Dictionary<Int32, IEnumerable<Order>> orderIdByCustomer
ILookup<Int32, Order> byCustomerId = orderList.ToLookup(o => o.CustomerId);
foreach (var customerOrders in byCustomerId)
{
Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
foreach (var order in customerOrders)
{
Console.WriteLine(" Order {0} is payed: {1}", order.OrderId, order.IsPayed);
}
}
// the same using old fashioned Dictionary
Dictionary<Int32, List<Order>> orderIdByCustomer;
orderIdByCustomer = byCustomerId.ToDictionary(g => g.Key, g => g.ToList());
foreach (var customerOrders in orderIdByCustomer)
{
Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
foreach (var order in customerOrders.Value)
{
Console.WriteLine(" Order {0} is payed: {1}", order.OrderId, order.IsPayed);
}
}
// lookup Order by payment status (1:m)
// would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
IEnumerable<Order> payedOrders = byPayment[false];
foreach (var payedOrder in payedOrders)
{
Console.WriteLine("Order {0} from Customer {1} is not payed.", payedOrder.OrderId, payedOrder.CustomerId);
}
}
class Order
{
// key properties
public Int32 OrderId { get; private set; }
public Int32 CustomerId { get; private set; }
public Int32 Year { get; private set; }
public Boolean IsPayed { get; private set; }
// additional properties
// private List<OrderItem> _items;
public Order(Int32 orderId, Int32 customerId, Int32 year, Boolean isPayed)
{
OrderId = orderId;
CustomerId = customerId;
Year = year;
IsPayed = isPayed;
}
}
}
}
Remark on Immutability
By default, Lookups are kind of immutable and accessing the internal
s would involve reflection.
If you need mutability and don't want to write your own wrapper, you could use MultiValueDictionary
(formerly known as MultiDictionary
)
from corefxlab (formerly part ofMicrosoft.Experimental.Collections
which isn't updated anymore).
I've managed to achieve it with minimal effort (just as simple as with ASP.NET Core).
For that I use OWIN Startup.cs
file and Microsoft.Owin.Security.Jwt
library.
In order for the app to hit Startup.cs
we need to amend Web.config
:
<configuration>
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
...
Here's how Startup.cs
should look:
using MyApp.Helpers;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
[assembly: OwinStartup(typeof(MyApp.App_Start.Startup))]
namespace MyApp.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigHelper.GetAudience(),
ValidIssuer = ConfigHelper.GetIssuer(),
IssuerSigningKey = ConfigHelper.GetSymmetricSecurityKey(),
ValidateLifetime = true,
ValidateIssuerSigningKey = true
}
});
}
}
}
Many of you guys use ASP.NET Core nowadays, so as you can see it doesn't differ a lot from what we have there.
It really got me perplexed first, I was trying to implement custom providers, etc. But I didn't expect it to be so simple. OWIN
just rocks!
Just one thing to mention - after I enabled OWIN Startup NSWag
library stopped working for me (e.g. some of you might want to auto-generate typescript HTTP proxies for Angular app).
The solution was also very simple - I replaced NSWag
with Swashbuckle
and didn't have any further issues.
Ok, now sharing ConfigHelper
code:
public class ConfigHelper
{
public static string GetIssuer()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
return result;
}
public static string GetAudience()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Audience"];
return result;
}
public static SigningCredentials GetSigningCredentials()
{
var result = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
return result;
}
public static string GetSecurityKey()
{
string result = System.Configuration.ConfigurationManager.AppSettings["SecurityKey"];
return result;
}
public static byte[] GetSymmetricSecurityKeyAsBytes()
{
var issuerSigningKey = GetSecurityKey();
byte[] data = Encoding.UTF8.GetBytes(issuerSigningKey);
return data;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey()
{
byte[] data = GetSymmetricSecurityKeyAsBytes();
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins()
{
string result = System.Configuration.ConfigurationManager.AppSettings["CorsOrigins"];
return result;
}
}
Another important aspect - I sent JWT Token via Authorization header, so typescript code looks for me as follows:
(the code below is generated by NSWag)
@Injectable()
export class TeamsServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "https://localhost:44384";
}
add(input: TeamDto | null): Observable<boolean> {
let url_ = this.baseUrl + "/api/Teams/Add";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(input);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + localStorage.getItem('token')
})
};
See headers part - "Authorization": "Bearer " + localStorage.getItem('token')
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.