text:
Q: Spring Boot test entity field validation with custom validation Setup:

*

*Spring Boot 2.3.3 (spring-boot-starter-validation)

*JUnit 5 Jupiter

*Lombok

Entity fields can be annotated with simple javax.validation constraints like @Positive.
@Entity
@Data
@Builder
public class Person {
    @Id
    @GeneratedValue
    private long id;

    @Column
    @Positive(message="not positive")
    private int age;
}

This can be tested quite easily:
public class PersonTest {

    private Validator validator;

    @BeforeEach
    public void before() {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    @Test
    public void invalid_becauseNegativeAge() {
        Person uut = Person.builder().age(-1).build();
        Set<ConstraintViolation<Person>> actual = validator.validate(uut);
        assertThat(actual.iterator().next().getMessage()).isEqualTo("not positive");
    }
}

Now I add a custom validator to Person:
@Entity
@Data
@Builder
public class Person {
    @Id
    @GeneratedValue
    private long id;

    @Column
    @Positive(message="not old enough")
    private int age;

    @ComplexValueConstraint
    private String complexValue;
}

Custom annotation:
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ComplexValueValidator.class)
public @interface ComplexValueConstraint {

    String message() default "too simple";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Custom validator:
class ComplexValueValidator implements ConstraintValidator<ComplexValueConstraint, Person> {

    @Override
    public boolean isValid(final Person person, final ConstraintValidatorContext context) {
    String complexValue = person.getComplexValue();
    if (complexValue.length() < 5) {
        return false;
    }
    return true;
    }
}

Now, my test from above fails with a
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'ComplexValueConstraint' validating type 'java.lang.String'. Check configuration for 'complexValue'

How can I make this test to work again? I know I could test the validator in isolation, but then my simple annotations like @Positive would remain untested.
Is it because I create the validator in the test class manually? @Autowired won't work somehow.

A: You are declaring that ComplexValueValidator validates objects of type Person:
ComplexValueValidator implements ConstraintValidator<ComplexValueConstraint, Person>

but the annotation is applied to a field of type String instead of a field of type Person:
@ComplexValueConstraint
private String complexValue;

Hence the message that the constraint can not be applied to a java.lang.String.
Try changing complexValue to be of type Person instead of type String.


text:
Q: Pass query variable to a MSDB.dbo.sp_Send_DBMail I have written a SQL query. But its giving me an error.
DECLARE @Delimiter Char(1)
SET @Delimiter = CHAR(9)
EXEC MSDB.dbo.sp_Send_DBMail
@profile_name = 'K2MailSetup',
@Recipients='test@xyz.com',
@Subject='Extraction Report',
@Body='Hi',
@Query='set nocount on;
Select Coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type,
 try_convert(xml, col).value(''(/collection/object/fields/field/value)[1]'', ''varchar(3)'')
from (select col= Coalesce(replace(replace(A.[business_line], char(10), ''''), char(13), ''''),'''')
    FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A'

Error states

Msg 102, Level 15, State 1, Line
  Incorrect syntax near '/'.

A: I found 2 issues here.

*

*your subquery is not properly closed

*your quotes are not property terminated

Declare @Query as nvarchar(1000)
Set @Query='set nocount on;
            set QUOTED_IDENTIFIER on;
            Select try_convert(xml, Coalesce(replace(replace(A.[business_line], char(10), '''''''')
                        , char(13), ''''''''),''''''''))
                        .value(''(/collection/object/fields/field/value)[1]'', ''varchar(3)'')
                , Coalesce(replace(replace(A.[type], char(10), ''''''''), char(13), ''''''''),'''''''') as [Type]
                from [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A;'

A: The trick to dynamic SQL is to make sure the SQL works before trying to make it dynamic.
Your query needs multiple tweaks before it works as a basic SQL query:
set nocount on;

select coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type
  , try_convert(xml, col).value('(/collection/object/fields/field/value)[1]', 'varchar(3)')
from (
    select col = coalesce(replace(replace([business_line], char(10), ''''), char(13), ''''),''''), Type
    FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS]
) A;

Then and only then, convert to dynamic SQL by doubling all single quotes:
declare @Query as nvarchar(1000) = 'set nocount on;

select coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type
  , try_convert(xml, col).value(''(/collection/object/fields/field/value)[1]'', ''varchar(3)'')
from (
    select col = coalesce(replace(replace([business_line], char(10), ''''), char(13), ''''),''''), Type
    FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS]
) A;'

exec(@Query);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rules in lint.xml are ignored after updating Android gradle plugin from 2.2.3 to 2.3.0 In my project I have a lint.xml file (in the root of the application module directory). It is a simple one:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!--needed by retrofit, because in it okio.Okio is referencing java.nio.file, but it is not included in Android-->
    <issue id="InvalidPackage" severity="warning" />
</lint>

It all use to work as expected until I did the following upgrades:
com.android.tools.build:gradle:2.2.3 -> com.android.tools.build:gradle:2.3.0

With the v2.3.0 of the plugin, the lint.xml is ignored and the build fails with InvalidPackage lint error.
If I add lint configuration in the build file directly:
lintOptions {
    warning 'InvalidPackage'
}

It again works fine, so to me it looks that the issue is related to reading the lint.xml file.
Anyone else had this problem?
UPDATE:
Adding specific file name to the lintOptions config in the build.gradle also makes the build pass, so it looks that the issue is related to the file name or path:
lintOptions {
    lintConfig file('lint.xml')
}


text:
Q: var_dump($nombre) print two times ajax + php slim framework why? I´ve my call a ajax
$("#box-modal").on("shown",function(event)
   {
       $("button#add-cart").click(function()
       {

           if($("#selectproductname").val()!=='-1')
           {
                var valueidproduct = $("#inputidproducto").val();
                var request = $.ajax({
                    type:'POST',
                    url: '/lineorder/addCart/'+valueidproduct,
                    data: $("#form-product").serialize(),
                    datatype:'html'
                    });
                request.done(function(html) {
                    $( "#editor-panel > div" ).html( html);
                });

                request.fail(function( jqXHR, textStatus ) {
                    alert( "Request failed: " + textStatus );
                });
            }

When I call a my route php, and I want to get the result of a variable print two times why?. I only want one time.
$app->post('/lineorder/addCart/:id',function($id) use($app)
{
       $str='';
       //compruebo si el array de sesion del carrito era creado si no es creado procedemos a crearlo
       if(!isset($_SESSION['cart-items']))
       {

           $_SESSION['cart-items'] = array();
       }
       $cantidad = $app->request()->post('inputcantidad');
       $nombre = $app->request()->post('inputnombre');
       var_dump($nombre);die();

In my
request.done(function(html)
{
   $("#editor-panel > div").html(html);
}

print two times the result;
What´s the fix?
What I do wrong?


text:
Q: Specifying template filenames for template.ParseFiles My current directory structure looks like the following:
App
  - Template
    - foo.go
    - foo.tmpl
  - Model
    - bar.go
  - Another
    - Directory
      - baz.go

The file foo.go uses ParseFiles to read in the template file during init.
import "text/template"

var qTemplate *template.Template

func init() {
  qTemplate = template.Must(template.New("temp").ParseFiles("foo.tmpl"))
}

...

Unit tests for foo.go work as expected. However, I am now trying to run unit tests for bar.go and baz.go which both import foo.go and I get a panic on trying to open foo.tmpl.
/App/Model$ go test
panic: open foo.tmpl: no such file or directory

/App/Another/Directory$ go test
panic: open foo.tmpl: no such file or directory

I've tried specifying the template name as a relative directory ("./foo.tmpl"), a full directory ("~/go/src/github.com/App/Template/foo.tmpl"), an App relative directory ("/App/Template/foo.tmpl"), and others but nothing seems to work for both cases. The unit tests fail for either bar.go or baz.go (or both).
Where should my template file be placed and how should I call ParseFiles so that it can always find the template file regardless of which directory I call go test from?

A: Helpful tip:
Use os.Getwd() and filepath.Join() to find the absolute path of a relative file path.
Example
// File: showPath.go
package main
import (
        "fmt"
        "path/filepath"
        "os"
)
func main(){
        cwd, _ := os.Getwd()
        fmt.Println( filepath.Join( cwd, "./template/index.gtpl" ) )
}

First off, I recommend that the template folder only contain templates for presentation and not go files.
Next, to make life easier, only run files from the root project directory. This will help make the path to an file consistent throughout go files nested within sub directories. Relative file paths start from where the current working directory, which is where the program was called from.
Example to show the change in current working directory
user@user:~/go/src/test$ go run showPath.go
/home/user/go/src/test/template/index.gtpl
user@user:~/go/src/test$ cd newFolder/
user@user:~/go/src/test/newFolder$ go run ../showPath.go
/home/user/go/src/test/newFolder/template/index.gtpl

As for test files, you can run individual test files by supplying the file name.
go test foo/foo_test.go

Lastly, use a base path and the path/filepath package to form file paths.
Example:
var (
  basePath = "./public"
  templatePath = filepath.Join(basePath, "template")
  indexFile = filepath.Join(templatePath, "index.gtpl")
)


text:
Q: What JS syntax is used for this function parameter? What kind of parameter is this? { children }: { children: JSX.Element }
This is the function declaration
function RequireAuth({ children }: { children: JSX.Element }) {
  let auth = useAuth();
  let location = useLocation();

  if (!auth.user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

I know that the function takes JSX component, but I still don't know which syntax the parameter uses.


text:
Q: Is there a AWS CDK code available to enable WAF logging for Kinesis firehose delivery stream? Anyone have Python CDK code to enable Amazon Kinesis Data Firehose delivery stream Logging in WAF? Any language CDK code is fine for my reference as I didn't find any proper syntax or examples to enable in official python CDK/api documentation nor in any blog.

A: From the existing documentation (as of CDK version 1.101 and by extension Cloudformation) there seems to be no way of doing this out of the box.
But there is API call which can be utilized with boto3 for example: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/wafv2.html#WAFV2.Client.put_logging_configuration
What you need to have in order to invoke the call:

*

*ResourceArn of the web ACL

*List of Kinesis Data Firehose ARN(s) which should receive the logs

This means that you can try using Custom Resource and implement this behavior. Given you have created Firehose and web ACL in the stack previously, use this to create Custom Resource:
https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.custom_resources/README.html
        crd_provider = custom_resources.Provider(
            self,
            "Custom resource provider",
            on_event_handler=on_event_handler,
            log_retention=aws_logs.RetentionDays.ONE_DAY
        )

        custom_resource = core.CustomResource(
            self,
            "WAF logging configurator",
            service_token=crd_provider.service_token,
            properties={
                "ResourceArn": waf_rule.attr_arn,
                "FirehoseARN": firehose.attr_arn
            }
        )

on_event_handler in this case is a lambda function which you need to implement.
It should be possible to simplify this further by using AwsSdkCall:
on_event_handler = AwsSdkCall(
        action='PutLoggingConfiguration',
        service='waf',
        parameters={
            'ResourceArn': waf_rule.attr_arn,
            'LogDestinationConfigs': [
                firehose.attr_arn,
            ]
    )

This way you don't need to write your own lambda. But your use case might change and you might want to add some extra functionality to this logging configurator, so I'm showing both approaches.
Disclaimer: I haven't tested this exact code, rather this is an excerpt of similar code written by me to solve similar problem of circumventing the gap in Cloudformation coverage.

A: I don't have python CDK example, but I had it working in Typescript using CfnDeliverySteam and CfnLoggingConfiguration. I would imagine you can find matching class in python CDK.


text:
Q: Wordpress, a good search plugin? I'm looking for Wordpress plugin that just improved the search results, but doesn't add the the search box.
At the moment wordpress isn't even doing plurals. So does anyone know a good plugin that will make the search a whole lot better?

A: Try using below plugins...
Use Relevanssi Plugin for Multilingual Support
  http://wordpress.org/extend/plugins/relevanssi/
Use WPSearch for well behave custom Search
  http://wordpress.org/extend/plugins/wpsearch/
Use Search-Everything for all type of Content Search
  http://wordpress.org/extend/plugins/search-everything/

A: http://wordpress.org/extend/plugins/relevanssi/ does full text, fuzzy match, partial match and supports quotes and category searches. It rebuilds its index after each post/page is added.

A: Well if you are looking for a WordPress Search Plugin that not only makes your website fully searchable but also searches through the content of attached files including PDF, DOC, DOCX and other formats are supported. Here is the solution of it https://fulltextsearch.org/. I recommend you to use that plugin.


text:
Q: Random wrong result from bitwise and operation in Java Following test fails for random i:
    @Test
    public void test() {
        for (int i = 0; i < 1_000_000; i++) {
            boolean isTrue = and128(new byte[] {-1});

            if (!isTrue) {
                fail("broken: " + i + " " + isTrue);
                break;
            }
            clearCache();
        }
    }

    private void clearCache() {
        for (int i = 0; i < 100; i++) {
            and128(new byte[] {(byte) i});
        }
    }

    public static boolean and128(byte[] byteData) {
        return ((byteData[0] & 128) > 0);
    }

Because of randomness, I would blame Java Runtime. If I inline the method and128, I cannot reproduce the problem. Also if I just pass one byte instead of byte array, test passes.
I am using OpenJDK 14.0.2. Issue seems to be fixed in 15.0.2. It still seems to be present in 15.0.1 and I cannot find a bug that would correspond to this.
EDIT: I added this "clearCache" method that just runs on the side and makes bug easier to reproduce. I guess it prevents some java optimization.


text:
Q: passing laravel orm to view I'm working with laravel 4 and am unsure about the best practice-- is it considered a good idea to pass the Eloquent object directly to the view, or is it best to use the toArray method on it before passing it in?
Eg. this:
public function index()
{
    $users  = Users::all();
    return View::make('users.index', array('users' => $users));
}

or this:
public function index()
{
    $users  = Users::all()->toArray();
    return View::make('users.index', array('users' => $users));
}

or something else entirely?

A: I think making an array from the object and wrapping it in another to pass to the view is an overhead, when you can directly pass the object to the view.
Try by
return View::make('users.index')->with('users', $users);

A: Sending the view just the object is perfectly acceptable and is what is encouraged in most cases.
return View::make('users.index')->with(array('users' => $users));

A: You should use:
$users  = Users::all();
return View::make('users.index')->with(array('users' => $users));

or even
return View::make('users.index')->with(array('users' => Users::all()));

in this case.
You don't need to convert your object to array. In your view (Blade or not) you can display object properties and not array elements and it's really fine to do that. Moreover you can also use accessor if you have set any and if you convert your object to array you won't be able to do that


text:
Q: How to make sure that an image doesn't disappear when tapped too many times? Swift 4 I am working on an app and I have an image that changes when you click on it. However, there is a bug in the app and if you accidentally click one too many time on it the image completely disappears. I want to set a maximum value to the variable integerValue so that it prevents it from being tapped further. Could someone please help me and give an answer in Swift 4?
Here is the code.
var integerValue = 1

The maximum value should be 9.
First time I update the variable:
@objc private func updateProgress() {
    integerValue += 1
    if integerValue < 10 {
     self.updateImage()
    UserDefaults.standard.set(integerValue-1, forKey: String(day))
    self.displayLabelScreen()
    }

Second time I update the variable:
@objc private func deleteProgress() {
        integerValue -= 1
        if integerValue > 0 {
            UserDefaults.standard.set(integerValue-1, forKey: String(day))
        self.updateImage()
        }
    }

A: Given the code you posted and the need to keep integerValue within the range 1-9, update your code as follows:
@objc private func updateProgress() {
    // Only increment if the new value will be 9 or less
    if integerValue < 9 {
        integerValue += 1
        self.updateImage()
        UserDefaults.standard.set(integerValue, forKey: String(day))
        self.displayLabelScreen()
    }
}

@objc private func deleteProgress() {
    // Only decrement if the new value will be 1 or more
    if integerValue > 1 {
        integerValue -= 1
        UserDefaults.standard.set(integerValue, forKey: String(day))
        self.updateImage()
    }
}


text:
Q: How to merge Primary object with child objects using and ID reference in Parent to each child I have a primary parent collection (Projects) and 2 child collections stored as arrays with objects.
Projects
const projects = {
  items: [
    {
      name: "Logo and Branding for Iron Kettle",
      skills: [
        "579b150756ea2dba79c1f09f",
        "579b150756ea2dba79c1f062"
      ],
      solutions: [
        "579b150756ea2dba79c1f09e",
        "579b150756ea2dba79c1f077"
      ],
      _cid: "579b150756ea2dba79c1efcb",
      _id: "579b150756ea2dba79c1f0af"
    },
    {
      name: "Snow shoot for media company",
      skills: [
        "579b150756ea2dba79c1f072",
        "579b150756ea2dba79c1f062"
      ],
      solutions": [
        "579b150756ea2dba79c1f09e",
        "579b150756ea2dba79c1f071",
      ],
      _cid: "579b150756ea2dba79c1efcb",
      _id: "579b150756ea2dba79c1f06a"
    }
  ],
  count: 12,
  limit: 100,
  offset: 0,
  total: 12
};

Skills
const skills = {
  items: [
    {
      name: "Logo Design",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f09f"
    },
    {
      name: "Brand Research",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f072"
    },
    {
      name: "Graphic Design",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f062"
    }
  ],
  count: 13,
  limit: 100,
  offset: 0,
  total: 13
};

Solutions
const solutions = {
  items: [
    {
      name: "Location research",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f09e"
    },
    {
      name: "Complete photo shoot",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f071"
    },
    {
      name: "Competition Analysis",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f077"
    }
  ],
  count: 19,
  limit: 100,
  offset: 0,
  total: 19
};

I need to return a new projects array with the skills and solutions id's populated with the actual object from the relevant array.
This would be the end result of one item the new array.
{
  name: "Logo and Branding for Iron Kettle",
  skills: [
    {
        name: "Logo Design",
        _cid: "579b150756ea2dba79c1efdf",
        _id: "579b150756ea2dba79c1f09f"
    },
    {
      name: "Graphic Design",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f062"
    }
  ],
  solutions: [
    {
      name: "Location research",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f09e"
    },
    {
      name: "Competition Analysis",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f077"
    }
  ],
  _cid: "579b150756ea2dba79c1efcb",
  _id: "579b150756ea2dba79c1f0af"
},

A: Try something like this:
projects.items.map(i => ({
    ...i,
    skills: i.skills.map(s => skills.items.find(skill => skill._id === s)),
    solutions: i.solutions.map(s => solutions.items.find(solution => solution._id === s))
}));


text:
Q: convert each row of dataframe to a list of tuples with column name and value as tuple I am trying to efficiently find a way to create a list of tuple for each row of the dataframe including the index. so what i am trying to do is basically for row1 create a list of tuple like [( index , array [2018-04-09 00:00:00 ] ) , ('A' , array [1] ) , ('B' , array [a] )] similarly a different list of tuple for row2 ,row3 and so on.
       index              A  B
     2018-04-09 00:00:00  1  a
     2018-04-09 00:20:00  2  b
     2018-04-09 00:40:00  3  c
     2018-04-09 01:00:00  4  d

I tried to do something like below:-
 for index,row in df.iterrows():
     print(list(row.itertuples(index=False)))

This gives me an error 'Series' object has no attribute 'itertuples'.
One way i can do is iterate over each row and individually create tuple for each column value and the add them to a list, but what i want to do is write precise and elegant code for it.
Thanks


text:
Q: Tomcat - отображение загруженных файлов на странице Всем привет. приложение на Tomcat, SpringBoot, Angular (тестовая машина виндовая)
Задача стандартная загрузить на сервер, сохранить, отобразить.
Есть страница для загрузки фоток на сервер. Фотки загружаются нормально в файловую систему с пазом "Е://path//to//files//img.jpg".
И вот вопрос в том что: как мне их потом достать из этого паза "Е://path//to//files//img.jpg" и отобразить на странице.
Статический контент из "resources" берется и отображается
На некотором ресурсе нашел решение для томката здесь и здесь но оно не сработало (или я его не понял)
<Context docBase="Е://path//to//files" path="/files" />

и потом это не отображется

Заранее благодарен за ответ!

A: И снова всем привет. Проблема решена, посредством настройки спринга в обход web.xml (в данной ситуации web.xml не используется), оригинал решения здесь
Код решения:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
    static String IMAGE_DIR = "E://path//to//files//";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/files/**").addResourceLocations("file:" + IMAGE_DIR);
        super.addResourceHandlers(registry);
    }
}

Далее в методе который сохраняет это дело паз пишем такой:
private static String PATH_FOR_UPLOADED = "E://path//to//files//";

а путь который будет храниться в БД такой:
private static String PATH_FOR_DATABASE = "./files/";

сохраняем как:
save(PATH_FOR_DATABASE + "any/else/path/" + "img.jpg")

ну и достаем, соответственно:

PS/ В принципе можно попытаться еще немного подшаманить: все эти пазы прописать в пропертях, что бы можно было их менять без перекомпиляции, но с редеплоем...


text:
Q: Is calling MemoryStream.ToArray() dangerous after disposing? In the below code, is there any chance the GC will clean out the MemoryStream so that ToArray will fail, since it is outside the using statement?
private static byte[] getBytes()
{
    MemoryStream ms = null;

    using (ms = new MemoryStream())
    {
        // ...
    }

    return ms.ToArray();
}

A: No, there's no chance of that. It's safe to do - the MemoryStream keeps a strong reference to the byte array.
I'll see if I can find any documentation about guarantees...
EDIT: Sort of...
From MemoryStream.Close:

The buffer is still available on a MemoryStream once the stream has been closed.

Admittedly that doesn't guarantee it for Dispose, but that's documented to call Stream.Close.
MemoryStream.Dispose(bool) could then be overridden to release the array, but it doesn't in my experience, and it would be a breaking change at this point.


text:
Q: Failed to echo on the same line after using sed I am reading a text file with the following code and I want to echo the output on the same line on screen. Preceding to that, I want to do some trimming with sed but at the end I failed to echo the output on the same line.
while read line; do {
     var="$(echo $line | sed 's/<[^>]*>//g')";
     echo -n "$var"
} done < file.txt

So if I echo -n "$line" it prints the output on the same line but when `sed' comes in it failed to do so. What is it that I am doing wrong ?


text:
Q: Why does SonarQube claim the `return` line is not covered by a unit test? Here's my API endpoint:
[HttpPost]
public int Post(SearchHistory searchHistory)
{
    IDashboardRepository dashboardrepos = new DashboardRepository();
    int historyId = dashboardrepos.SaveSearchHistoryByUser(searchHistory);
    return historyId;
}

And here is the SonarQube report:

The two green bars on lines 37 & 38 indicate that they are covered by the unit test. But for some reason like 39 isn't?
Here's the test:
[TestMethod()]
public void GlobalSeach_PutTest()
{
    SearchHistory history = new SearchHistory {
        // redacted for ease of reading on SO
    }
    var controller = new GlobalSearchController(_config);
    int? response = controller.Post(history);
    Assert.IsTrue(response != null);
}

A: Your Postmethod returns an int. On your test you are expecting to receive a nullable int (int?).
My gues is the problem is that your are not really testing the result of your method when you use this assert: Assert.IsTrue(response != null);. The first problem is that kind of test will never fail.
I imagine that your dashboardrepos.SaveSearchHistoryByUser method should return the primary key of the entity you just persist on your db. Based on that assumption I suggest you to refactoring your test as I describe below, to improve and solve the problem with coverage.
[TestMethod()]
public void GlobalSeach_PutTest()
{
    SearchHistory history = new SearchHistory {
        // redacted for ease of reading on SO
    }

    // _dashboardreposMock is an example of Mock<IDashboardRepository>
    _dashboardreposMock.Setup(_ => _.SaveSearchHistoryByUser(It.IsAny<SearchHistory>)).Returns(1);

    var controller = new GlobalSearchController(_config);
    int response = controller.Post(history);
    Assert.IsTrue(response == 1);
}


text:
Q: How to partition postgresql in django rest framework I want to partition a table in django rest framework which uses the postgresql database.
I am not being able to import Architect and django-postgres-extra packages. Can someone please help me to partition the table as I have a stock dataset with every stocks daily historical data, also each stock data will be added everyday. So I want to partition the table by stock Names so that each stock has its own table for faster lookup.

A: I'm can't give a detailed answer, since the model is not mentioned, yet I can give you a lead - use Django's magnificent aggregation functions✨ (like SQL's GROUP BY) you can aggregate by the stock name, and have all its related properties.
e.g. something like Stocks.objects.values(stock_name)
I hope my Breadcrumb trail will help you...


text:
Q: this is undefined en addEventListener Callback Hola tengo el siguiente código html:

        Ingresos

Letor

        Gastos

y el siguiente js:
function startMenu(){
    let menuButtons = document.getElementsByClassName('is-tab');

    for(let i=0; i<menuButtons.length;i++ )
        menuButtons[i].addEventListener('click',()=>{
            console.log(this);
        });
}

¿Hay alguna manera de acceder a this desde el callback o necesariamente tengo que agregar un parámetro en la funcion para buscar el target?

A: El problema se debe a que estas usando una función flecha (En ingles arrow function).

Las funciones de flecha capturan el valor de this del contexto actual

Solución:
Usar una función
Ejemplo:

function startMenu(){
    let menuButtons = document.getElementsByClassName('is-tab');

    for(let i=0; i<menuButtons.length;i++ )
        menuButtons[i].addEventListener('click',function(){
            console.log(this);
        });
}

    Ingresos

Letor

    Gastos

A: Efectivamente se puede obtener mediante un target

function startMenu(e){
     console.log(e.target.nodeName);

}

        Ingresos

Letor

        Gastos


text:
Q: Even after validation failed the new page is redirected I am implementing a simple code just to figure out why validation is not working in my browser.
But validation is not working. Idk y.
It is just redirecting to next page
newjsp.jsp
  <%@page contentType="text/html" pageEncoding="UTF-8"%>
  <!DOCTYPE html>
   <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script>
        function validation()
        {
            var a=document.form1.txt1.value;
            if(a=="")
            {
                alert("Hey");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
    <form id="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
    <input type="text" id="txt1">
    <input type="submit" id="sub">
  </form>
</body>

A: Update
Do not use this as a function parameter. this is a keyword. Use any other variable. Something like this
function validation(form) {
  var a=form.txt1.value;
  if(a==="") {
    window.alert("Hey");
    return false;
  }
  return true;
}

When the form is like this
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
....
</form>

Try document.forms.form1.txt1.value;
function validation(){
  var a=document.forms.form1.txt1.value;
  if(a==""){
     alert("Hey");
     return false;
  }
  return true;
}

Check the demo http://jsbin.com/vuxoha/1/edit

A: Use opposite logic - something must be OK, then turn TRUE, in all other cases, return FALSE.
function validation()
{
  var a = document.getElementById('txt1').value;
  if (typeof a != "undefined" && a != "")
  {
    // `a` is in very good condition :)
    return true;
  }

  alert('hey');
  return false;
}

I think, your document.form1.txt1.value is not filled correctly, so your value a is probably undefined and not "", so it will return TRUE.
Try to debug with console.log(a);
And finally, use var a = document.getElementById('txt1').value;, just in case :)

A: instead of form id use name
<script>
        function validation()
        {
            var a=document.form1.txt1.value;
            console.log(a);
            if(a=='')
            {
                alert("Hey");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
    <form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
    <input type="text" id="txt1">
    <input type="submit" id="sub">
  </form>
</body>


text:
Q: ag row group moves when scrolling I had a grid table with two group rows. The second one always moves and covers the next row when I scroll the table.
Before I scroll:

After I scroll:

Here is a screen shot of the DOM of the group row.

The ag-grid version is 18.1.1 and everything was just fine when I were in v16. The browser is chrome.

A: It seems that I did not update the ag-grid in a proper way (I downloaded the ag-grid zip file and recover it in my node_modules manually).
Problem solved by using npm (yarn) command to update.


text:
Q: How can I bold each cell with minimum value for each column in R Markdown I want to bold cells with minimum values for one of my data frames which I combined to be one. I want the minimum value in each column to be bolded.
The below R code shows my Minimum Working Example (MWE). The table consists of columns of five (5) randomly generated values from the normal distribution. The first three (3) show when std dev =1 while the last three (3) show when std dev =2. Each column is different based on its seed of generation and its std dev.
---
title: "Min Value to be Bolded"
output:  pdf_document
---

```{r}
set.seed(1)
df1 <- data.frame(
  seed1 = rnorm(5, mean = 0, sd = 1),
  seed2 = rnorm(5, mean = 0, sd = 1),
  seed3 = rnorm(5, mean = 0, sd = 1)
)
set.seed(1)
df2 <- data.frame(
  seed1 = rnorm(5, mean = 0, sd = 2),
  seed2 = rnorm(5, mean = 0, sd = 2),
  seed3 = rnorm(5, mean = 0, sd = 2)
)
df <- cbind(df1, df2)
df |>
  knitr::kable(format = "html", table.attr = "style='width:100%;'", digits = 2, align = 'c', caption = "5 Random Numbers from the Normal Dist at diff set and std dev") |>
  kableExtra::kable_styling(bootstrap_options = 'bordered') |>
  kableExtra::add_header_above(c('$sd = 1$' = 3, '$sd$ = 2' = 3)) |>
  row_spec(3, bold=T, hline_after = TRUE)
```

The output
Instead of me to get the minimum values bold. I got the third row bold all through. I can get the values on R like this:
lapply(df1, 2, FUN = min)

but I need help on how to get the cells bolded with kable or kableExtral.
Please note I do not mean to do that for the whole data frame, I only need it for just df1 or df2.

A: You may add library(formattable) and then
df |>
  lapply(\(x){ifelse(x == min(x), cell_spec(round(x,2), bold = TRUE), round(x,2))}) |>
  knitr::kable(format = "html", table.attr = "style='width:100%;'", digits = 2, align = 'c',
                caption = "5 Random Numbers from the Normal Dist at diff set and std dev",
                escape = FALSE) |>
  kableExtra::kable_styling(bootstrap_options = 'bordered') |>
  kableExtra::add_header_above(c('$sd = 1$' = 3, '$sd$ = 2' = 3))

Or, if you only want for df1 you may start by
df1 |> lapply(\(x){ifelse(x == min(x), cell_spec(round(x, 2), bold = TRUE), round(x, 2))}) |> cbind(df2) |>

And for df2
df1 |> cbind(df2 |> lapply(\(x){ifelse(x == min(x), cell_spec(round(x, 2), bold = TRUE), round(x, 2))})) |>

A remark: With my solution names of dataframe become all x. You could add as.data.frame after the lapply to get the original names, but in this case they become changed because df has the names duplicated which is not a suitable practice. Instead, using col.names you may write the desired ones, for example
df |>
  lapply(\(x){ifelse(x == min(x), cell_spec(round(x,2), bold = TRUE), round(x,2))}) |>
  as.data.frame() |>
  knitr::kable(format = "html", table.attr = "style='width:100%;'", digits = 2, align = 'c',
               caption = "5 Random Numbers from the Normal Dist at diff set and std dev",
               escape = FALSE, col.names = rep(c("seed1", "seed2", "seed3"), 2)) |>
  kableExtra::kable_styling(bootstrap_options = 'bordered') |>
  kableExtra::add_header_above(c('$sd = 1$' = 3, '$sd$ = 2' = 3))

Note also that as comment @phiver, I had to modify output:  pdf_document to output:  html_document, since otherwise code didn't work. To get a pdf, the last lines of the code should be as follows (then it works):
  knitr::kable(format = "latex",  digits = 2, align = 'c',
               caption = "5 Random Numbers from the Normal Dist at diff set and std dev",
               escape = FALSE, col.names = rep(c("seed1", "seed2", "seed3"), 2)) |>
  kableExtra::kable_styling(bootstrap_options = 'bordered', full_width = TRUE) |>
  kableExtra::add_header_above(c('$sd = 1$' = 3, '$sd$ = 2' = 3))


text:
Q: display: inline; and overlapping? I have the below. The error class comes from here http://css.dzone.com/news/css-message-boxes-different-me
I added display: inline to the div so it wouldnt take up the whole row. However now instead of going onto the next row it stays on the same row and is drawn on top of links or the login form. How do i properly handle this? I dont know if i should add a
 (if that works) or change the property css.

<form action="/login" method="Post">

<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">

</form>

Error back - Title

A: display:inline makes it behave as if it's just another item that works into the normal text flow of the page. Thus, if you want it to be forced down to the next line, then yes, you'll want to add a
. However, if you simply want to limit the width of the error message box but still have it on its own line, you probably don't want display:inline in the first place - instead, you'd just want to set the width: property to however large you want the box to be (for instance, width:500px; for 500 pixels wide, or width:50%; for half the width of the containing element).


text:
Q: How to update meta_value to wp_postmeta I'm make a my plugin. I want update this value
a:1:{i:0;s:22:{"include/archive/author";}

up to wp_postmeta tables with update_post_meta() method.
But İt is adding value while added addional value my meta value
s:41:"a:1:{i:0;s:22:{"include/archive/author";}";
How to adding only my value
a:1:{i:0;s:22:{"include/archive/author";}

Thanks.

A: The issue is that you are serializing a serialized string.
Your original array looks like this :
array(0=>'include/archive/author');

You're probably doing something like this:
update_post_meta($post_id,$meta_key,$author);

where you meant to do this:
update_post_meta($post_id,$meta_key,$author[0]);


text:
Q: How to control the concurrency in flask? I have developed the Flask application, live on AWS EC2 Instance and i have increased the number of worker and threads like below:
gunicorn.... --worker=2 --thread=4

What i understand so far from sites that it may create the 4 parallel request for single worker in 1 core of CPU and same for other. Eventually you will be getting 8 requests per second.
As i am multithreading so i was bit hesitated that my app responses should not get mixed up or does not overwrite some other requests results as i am saving some things on disk too:
Here is brief overview of app
app = Flask(__name__)
app.route('/route1'):
    #ML Model processing
    return jsonify{'Result'}
app.route('/route2'):
    #ML Model 2 processing
    #Save image to folder and then process ml model on it
    return jsonify{'Result'}

Note: Here i have created only single folder which will gonna overwrite image for each request.
So to not get mixed up for any results not for just this one but also for first one , I want to know what is good ?
I have heard about Lock, Semaphores but what you suggest ?. Which method is best ? I think i am doing concurrency and I want to take control


text:
Q: How to add navlink event hander by render tree builder? Could someone help me in adding event handler on NavLink?
HTML I want to make:
  <NavLink class="nav-link" href="/" @onclick="()=>GetIsClicked("home")">
      Home
  </NavLink>

@code{
    public void GetIsClicked(string str) {

  }
 }

RenderTreeBuilder Code:
 protected override void BuildRenderTree(RenderTreeBuilder builder) {
    builder.OpenComponent<NavLink>(1);
    builder.AddAttribute(2, "class", "nav-link");
    builder.AddAttribute(3, "href", "/");
    // here I want to add attribute for @onclick="()=>GetIsClicked("home")"
    builder.AddAttribute(4, "ChildContent", (RenderFragment)((builder2) => {
                builder2.OpenElement(5, "span");
                builder2.AddAttribute(6, "aria-hidden", "true");
                builder2.AddAttribute(7, "class", "oi oi-home");
                builder2.CloseElement();
                builder2.AddContent(8, "Home");
    }));
    builder.CloseComponent();
    builder.CloseElement();
    builder.CloseElement();
 }

Thanks in advance.
Joon

A: You can do that like this:
 __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(1);
            __builder.AddAttribute(2, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, ()=>GetIsClicked("home")));


text:
Q: move semantics with const object I have code like this:
class Pair{
public:
    Pair(Pair && other){};

    Pair(Pair & other){};
};

class IROList{
public:
    virtual const Pair get(const char *key) const = 0;

    inline const Pair operator[](const char *key) const{
        return this->get(key);
        // error: binding 'const Pair' to reference of type 'Pair&&' discards qualifiers
    }
};

when compiled, it produce
error: binding 'const Pair' to reference of type 'Pair&&' discards qualifiers

if I change move constructor to const, error dissipated.
    Pair(const Pair && other){};

However, if move constructor takes const, I can not really move the data. I should copy it.
Is there any workaround except removing the const of returning methods, e.g.
    virtual Pair get(const char *key) const = 0;
    inline Pair operator[](const char *key) const;

A: The problem is you didn't implement your copy constructor well.
instead of :
Pair(const Pair & other){};

you wrote
Pair(Pair & other){};

this causes the constructor to accept only l-value variables, no temporaries, since only const references can bind to temporaries and r-value references.
this forces the compiler to return Pair from get as a r-value-reference (move semantics) since it returns a temporary and it doesn't know how to copy it, only how to move it. again, a temporary can be caught only by const reference or r-value-reference.
r-value-references are not const - this is their all existence! to be caught and their content would be stolen by another object .
to prove my point , here is GCC compiler output with your code (no const):
http://coliru.stacked-crooked.com/a/c390189089434f30 - doesn't compile
and with the const:
http://coliru.stacked-crooked.com/a/0db0fc767e6f10f2  - no compiler errors.
further than that, I whould suggest you to look at std::map implementation or similar classes. there is somewhat agreement between developers on how operator [] should look like and what it returns and why.
good software design is far more important then very specific features like move sematincs.

A: You cannot move a const object as a move operation is a modification.  When you move you swap the contents of the old object into the new object.  this in turn puts the indeterminate value of the new object into the old object.  You could not do that if the old object is const as you would not be able to write to it.
When you use move semantics you want to pass by value.  When you pass by value you make a copy that will never be accessed so you are free to move from it.  See: Is pass-by-value a reasonable default in C++11?

A:
Is there any workaround except removing the const of returning methods

No. Returning const values in this case is silly and pointless as the user can simply make a mutable copy at will. You only prohibit optimizations and good semantics (e.g. move semantics) by making it const.
Removing the const isn't a "workaround", it's what should be done irrespective of the issues with move semantics.


text:
Q: Rotate a given matrix by K times To rotate a matrix by K times means shifting the columns of the given N*N matrix to the right by K places.
For example, consider a 3*3 matrix, which has to be rotated.
Input:
n = 3;
k = 2;

Matrix before Rotation:
10  20  30
40  50  60
70  80  90

Expected output:
20  30  10
50  60  40
80  90  70

Actual output:
Segmentation fault (core dumped)

I don't know where am getting it wrong. Please sort it out. :(
Below is my attempt.
#include <stdio.h>

int main()
{
    int n,i,j,k,temp=0;
    scanf("%d",&n);
    int arr[n][n];
    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
         scanf("%d",&arr[i][j]);
       }
    }
    scanf("%d",&k);

    for(int l=1;l<=k;l++){
    temp=arr[i][0];
    for(int i=0;i<n;i++){
        for(int j=1;j<n-1;j++){
            arr[i][j]=arr[i][j+1];
        }
    }
    arr[i][j]=temp;
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            printf("%d",arr[i][j]);
        }

    }

    return 0;
}

A: The Solution
#include <stdio.h>

int main ()
{
    int n = 0, k = 0;

    while(n > 100 || n <= 0)//to prevent absurd values. Adjust as required
    {
        printf ("Enter length of matrix: ");
        scanf ("%d", &n);
    }
    printf ("Enter shift times: ");
    scanf ("%d", &k);
    k = k % n;//get rid of excess shifts
    k = n - k;//convert shift direction (right to left)
    int arr[n][n];
    printf ("Enter elements of matrix:\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            scanf ("%d", &arr[i][j]);//populates the matrix
        }
    }

    int temp[n][k];//for storing part of matrix while swapping
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < k; j++)
        {
            temp[i][j] = arr[i][j];//stores part of matrix
        }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = k; j < n; j++)
        {
            arr[i][j - k] = arr[i][j];//moves remaining part of matrix
        }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = n - k; j < n; j++)
        {
            arr[i][j] = temp[i][j - (n - k)];//places stored part in position
        }
    }

    printf ("The matrix:\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            printf ("%d\t", arr[i][j]);//prints the matrix
        }
        printf("\n");
    }

    return 0;
}

The explanation
Did you ever think what would happen if the value of k were greater than i?
The line k = k % n deals with it. It changes the number of right shifts to the minimun number of right shifts required.
The line k = n - k changes the number of right shifts to the equivalent number of left shifts. This is required as the our code left shifts the matrix by k columns.
Why? Because I wanted it to do so.
Note that the code following the statement int temp[n][k]; is very similar to what we write to swap two variables using a third.
temp = a;
a = b;
b = temp;

Finally, we print our matrix.
Note:
The program has been written in a way that is easy to read and  understand. It has not been optimized for performance.


text:
Q: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' I'm new to Ubuntu.
I have xampp installed on Ubuntu and works just fine. But when I am trying to run mysql -u username -p pass from terminal I recieve this error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'.

I've tried to install mysql-server again but it runs completely separate (has another database....and is not working with phpmyadmin from xampp).
How can I make it work in terminal from xampp server?

A: Your mysql-database might not be running at all!
Try this: sudo /etc/init.d/mysql start then mysql -u yourusername -p yourpasswrd


text:
Q: 12gb of ram but windows 10 says 3.48gb is usable I have recently upgraded my windows 10 laptop from 4gb to 12gb of ram. However, windows says that 3.48 gb is usable. This was also the case when I had only 4gb installed.
I just checked the BIOS and ran a memory check that took around 30 minutes. But it said that the memory was fine, and windows boots just fine as well.
SYSTEM INFO:

Bios Version: F.44
Bios Vendor: Insyde
Bios Setup Utility: InsydeH20 setup Utility
Bios Setup Utility Revision: 3.5
Processor: AMD(r) A6-3420M APU With AMD Radeon(r) HD 6520G Graphics
Graphics: AMD Radeon(r) HD 6520G Graphics
Ram: 12.0GB, 3.48GB Usable by Windows
Operating System: Windows 10
Architecture: ACPI x64

Added Ram: 8GB Green Rasalas Ram from Amazon
Motherboard: Unknown
In conclusion, should I be worried? Is this just a bug with Windows 10 Update 1909? Does it mean that the Rasalas 8GB Ram Stick in my computer is unusable?
EDIT: I was looking around, and I discovered that a whopping 8.5 gb is hardware reserved!
EDIT2: I just swapped the ram cards, nothing happened. I had a suspicion that it was that, but I guess not.

A: According to the
HP Pavilion dv6 Entertainment PC Maintenance and Service Guide,
these are the possible memory configurations for the HP Pavilion DV6-1355dx:

The maximum is then 8 GB (2 x 4 GB), so the additional 8 GB RAM that you
bought cannot work for you. I suggest returning it to the shop.
I think that the most you can add is one RAM stick of 4 GB, as you already
have one installed. It is best if the one you buy is of the exact same
model as the one that came with the computer.
This is to ensure that dual-channeling will work to improve performance.
Otherwise, as fitting RAM to motherboard is quite complicated,
it is safer to use a scanner such available from
Crucial
that will detect your existing computer hardware and suggest a memory
upgrade.

(old answer)
One possibility is that for some reason the 8.5 GB that are hardware reserved
are actually allocated to the integrated display adapter.
Being integrated, this adapter has no Video RAM (VRAM) of its own and uses
part of your RAM.
To view the amount of video RAM in Windows 10:

*

*Run Settings > System > Display

*Click Advanced display settings

*Select the monitor and click its link for Display adapter properties

*The video RAM is listed in the Adapter tab next to "Dedicated Video Memory:".

If the amount of VRAM is excessive, this can be changed in the BIOS and may be called
something close to "Graphics Settings", "Video Settings", or "VGA Share Memory Size".
If you find nothing, check the Windows registry for the key
HKEY_LOCAL_MACHINE\Software\Intel\GMM. If the key exists and has an item
named DedicatedSegmentSize which contains the reserved amount in megabytes.
Its supposed maximal value is 512, which equals only 512 MB, but check it anyway.
If you still have found nothing, then the RAM you bought probably does not fit
the motherboard (a mistake that is easy to do).


text:
Q: C++ Code::Blocks making libraries on Windows So I'm using Code::Blocks right now as my IDE on Windows 10 and I made a small library with one little function.
Code::Blocks made me a .a file.
I then made a little test project that uses the library. Added it to my project build options in Linker Settings, and added its directory to my search directories. Great.
I can see the header file I made for the library so that's working.
I then try to use the function and I'm getting an 'undefined reference' for that function call.
So..I'm going to assume Windows doesn't understand how to load libraries with the '.a' extension? I believe Windows uses .lib files instead but I'm not sure how else I'm supposed to compile a .lib file in Code::Blocks as there's no template for it.
I am extremely new to Code::Blocks and making libraries in general.

A: Solved. Problem was when renaming the file from "main.c" to "main.cpp", Code::Blocks does not automatically change the compiler variable.
This was done by going into the file properties in the IDE and changing the variable from "CC" to "CPP".


text:
Q: Search for job titles in an article using Spacy or NLTK I'm new to NLP and recently been playing with NTLK and Spacy. However, I could not find a way to search for job titles (ex: product manager, chief marketing officer, etc) in an article.
Example, I have 1000 articles and I want to get all the articles that have job titles that I am interested in.
Also, what entity type does job titles fall in? I check https://spacy.io/docs/usage/entity-recognition and did not see it in there. I there a plan to add it?
Thanks.

A: "Job Titles" entity is not supported by Spacy NER, as also stated by Nathan. But you can create a custom named entity for your use case. Here is official documentation link. You can find step by step guide to train Spacy NER there.
You would need labeled data to train your NER. Generally you would need atleast 4000-5000 examples for train and 2000 examples for test. The more training data you have, the better will be the NER performance.
Here is some sample training data.
TRAIN_DATA = [
    ('Who is Shaka Khan?', {
        'entities': [(7, 17, 'PERSON')]
    }),
    ('I like London and Berlin.', {
        'entities': [(7, 13, 'LOC'), (18, 24, 'LOC')]
    }),
    ('I work as software engineer.', {
        'entities': [(9, 18, 'JOBTITLE')]
    }),

]

A: Stanford NER supports Titles (not perfect though). See demo page at http://corenlp.run/


text:
Q: Deploying an Application on Mac OS X doesn't work I can build a project and have it run fine on my computer but when I run it on different computers it wont work. How can I build it with Qt so that all files libraries get included?
I am following this http://doc.qt.digia.com/4.7/deployment-mac.html
but it doesn't seem to work. When I run qmake it just prints out the instructions for them like

Mode:
  -project       Put qmake into project file generation mode
                 In this mode qmake interprets files as files to
                 be built,
                 defaults to *.c; *.ui; *.y; *.l; *.ts; *.xlf; *.qrc; *.h; *.hpp; *.hh; *.hxx; *.H; *.cpp; *.cc; *.cxx; *.C
                 Note: The created .pro file probably will
                 need to be edited. For example add the QT variable to
                 specify what modules are required.
  -makefile      Put qmake into makefile generation mode (default)
                 In this mode qmake interprets files as project files to
                 be processed, if skipped qmake will try to find a project
                 file in your current working directory

I run it inside the release directory for the app. What am I doing wrong?

A: qmake on Mac OS X by default generates (deprecated) XCode project file. If you want to generate makefiles you need to run qmake with parameters:
qmake -spec macx-g++

Then you can call make. But if you want to deploy your app you need to run macdeployqt found in QTDIR/bin/ directory


text:
Q: Emacs ace jump mode: how to scroll? As far as I can tell, ace jump will only jump to items found in the visible part of the buffer.  Once I activate ace jump, and matches to my selection are highlighted, I can jump to any of them, as long as they are visible.  But what do I do if I want to find matches in the part of the buffer that it not visible?  Attempts to scroll the buffer causes ace jump to quit.

A: What you want seems like a good idea, but it doesn't really work. You would need to know what keypress you need to get to an off-screen match, and you can't know what those are because they are off-screen. Ace-jump is for jumping around the visible buffer.
Other options are isearch, M-x occur or structured tools like imenu, speedbar, ecb and so on.


text:
Q: Jquery select which children to show I have following html

    Bar1
    Bar2

let's say .foo is hide in default, then I just want to show .foo and his child .bar1. How to do this in jquery?
I have this in my jquery
$('#' + id).children(".foo //anything I can do here to select ONLY bar1 to show? ").show();

A: I would hide all children and just show bar1. See below,
var $foo = $('.foo');    //cache foo
$foo.children().hide();  //hide all foo's children
$foo.show();             //show foo
$foo.find('.bar1').show();  //show bar1

A: This would work.
$('#' + id).find(".foo .bar1").show();

A: $(".foo").show();
$(".foo").children(".bar1").show();

$(".foo").children("not:(.bar1)").hide();//if not hidden

A: u can type
$('.foo').toggle();

to display or hide the foo div container.
to select the bar 1 u can select $('.foo > .bar1').somefunction() or $('.foo').children('.bar1').somefunction();
there are so many different ways to select your elements... u can also use .hide() or .show() to manage if your element is hidden or not
always a nice link btw: http://api.jquery.com/


text:
Q: subnavbars inside a navbar html css I want to align the Login button with the settings icon along a line above the links from my navbar.
How can i achieve this?
Here's a fiddle that illustrates exactly my problem:
FIDDLE
and the code i wrote:

        Login

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

          Processes

          Reports

          Alerts

          Scheduler

          Admin

          Details

          Create

          Details

          Assistance

CSS:
* {
  font-family: 'Source Sans Pro', sans-serif;
}

.navbar-default .navbar-nav > li > a {
 color: white;
}

.navbar-default {
 background-color: black;
 border-color: black;
}

.navbar-default .navbar-nav > li > a:focus,
.navbar-default .navbar-nav > li > a:hover {
  color: white;
}

.navbar-default .navbar-nav > li > a {
  outline: none;
}

#nav_login {
  height: 10px;
  font-size: 10px;
}

#settings_icon {
  color: white;
  font-size: 1.5em;
}

EDIT:
Sorry, maybe i didn't explained myself well, but i want the login to be alongside the settings icon where it originally was (in the upper right corner)

A: Easier then you think, wrap it in an anchor ;)

I assume it has to be a link anyway, right?

A: Working Fiddle: http://jsfiddle.net/804jeg82/545/
I just added this on your css.
.navbar-nav {
  display: flex;
  align-items: center;
}

This is flexbox technique.
More about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Hope it helps you. Cheers mate!

A: just remove the top padding on the login anchor :
#nav_login a { padding-top : 0; }

A: Small changes
HTML:

        Login

CSS:
.nav.navbar-nav.right{
  display: flex;
  align-items: center;
 }
 .nav.navbar-nav.right li a{
   padding: 0 10px;
 }

Here is the updated Demo

A: You can also add
margin-top: 16px

to your "#settings_icon" id. It would also solve your problem if you are just looking to align the icon.
Here is the link:http://jsfiddle.net/804jeg82/548/


text:
Q: Using the "&" (ampersand) operator where the top-most parent is an element tag selector I have this LESS:
LESS
custom-component {
  .random-class {
    .decorator-class& wrapper {
      ...
    }
  }

that yields
CSS
.decorator-classcustom-component .random-class wrapper {
  ...
}

which outputs gibberish because there is no such class .decorator-classcustom-component. This happens because the uppermost parent selector is an HTML element tag and not a class or other selector type.
Is there a way to get the characters before the ampersand (.decorator-class) to concatenate on the right side of the uppermost parent selector? Like this:
custom-component.decorator-class .random-class wrapper

?
Note that attempting,
custom-component {
  .random-class {
    &.decorator-class wrapper {
//  ^ ampersand at the beginning of selector
      ...
    }
  }

would yield,
custom-component .random-class.decorator-class wrapper

A: I find it really useful to translate CSS selectors to English for debugging in situations like this. Your desired selector custom-component.decorator-class .random-class wrapper translates to:

Select wrapper elements inside an element with a class random-class, inside a custom-component element with the class .decorator-class.

If that's what you mean, then you need something like this:
custom-component {
  &.decorator-class {
    .random-class wrapper {
      ...
    }
  }


text:
Q: Most elegant way to do string conversion in Haskell See this related SO question: Automatic conversion between String and Data.Text in haskell
Given a string of type Text, I want to produce a lazy bytestring.
This works, but I wondered whether it's optimal, given the fact that both Text and the lazy bytestring have the property of being "string-like" and I still use the not-generic unpack:
import qualified   Data.ByteString.Lazy (ByteString)
import             Data.Text            (Text, unpack)
import             Data.String          (fromString)
import             Data.Text            (unpack)

convert :: IsString str => Text -> str
convert = fromString . unpack

I found the package string-conversions that offers the polymorphic function
 convertString :: a -> b

as part of the ConvertibleStrings typeclass.
While it works fine, I am suspicious: Why would I need an extra package for that? Couldn't there be already a typeclass like IsString that offers a toString method and in combination a universal convert function fromString . toString?

A: [Ok, while I was editing my question, a possible answer dawned to me]
On the hackage-page of string-conversions it says:

Assumes UTF-8 encoding for both types of ByteStrings.

So there are assumptions that go along with conversions and a universal conversion of string-like types might not be desirable.
Also performance probably depends on the input and output types and a universal conversion would pretend that it's all the same.
So my take on best practice is now this, being explicit rather than polymorphic:
import           Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as ByteString
import qualified Data.Text.Encoding   as Text

convert :: Text -> ByteString
convert = ByteString.fromStrict . Text.encodeUtf8


text:
Q: Lodash has no method 'remove' I'm following an example on websockets from my book:
var _ = require('lodash')
var ws = require('ws')
var clients = []

exports.connect = function(server) {
    var wss = new ws.Server({server: server})

    wss.on('connection', function(ws) {
        clients.push(ws)

        ws.on('close', function() {
            _.remove(clients, ws)
        })
    })
}

exports.broadcast = ...

The above snippet adds new websocket clients to the clients array. When a client closes the connection, it removes it from the list. I'm getting the following error on the _.remove(clients, ws):
TypeError: Object function lodash(value) {
    // exit early if already wrapped, even if wrapped by a different `lodash` constructor
    if (value && typeof value == 'object' && value.__wrapped__) {
      return value;
    }
    // allow invoking `lodash` without the `new` operator
    if (!(this instanceof lodash)) {
      return new lodash(value);
    }
    this.__wrapped__ = value;
  } has no method 'remove'
    at WebSocket.<anonymous> (/home/user/Projects/socialapp/websockets.js:15:6)
    at WebSocket.EventEmitter.emit (events.js:117:20)
    at WebSocket.cleanupWebsocketResources (/home/user/Projects/socialapp/node_modules/ws/lib/WebSocket.js:926:10)
    at Socket.EventEmitter.emit (events.js:117:20)
    at net.js:441:14
    at process._tickCallback (node.js:415:13)

That's definitely the way it's done in my book, and I don't understand why I'm getting that error as the remove method definitely exists.
EDIT: I'm using lodash v. 3.10.1

A: There might be some issue related to your lodash version. Try to do it this way:
var _ = require('lodash')
var ws = require('ws')
var clients = []

exports.connect = function(server) {
    var wss = new ws.Server({server: server})

    wss.on('connection', function(ws) {
        clients.push(ws)

        ws.on('close', function() {
            clients = _.without(clients, ws)
        })
    })
}

or you can simply do the same using plain old javascript
clients = clients.filter((client) => client !== ws);


text:
Q: Breaking up a list of lists I have a list of values stored in SortedLat, where SortedLat is a list of 74 sublists, and each sublist has its first element be a string. As you can see I am trying to create the first column for a table with these strings.
TableOfValues1 = Prepend[q, {"B1", "B2"}]
TableOfValues2 =
 MapThread[
  Prepend, {TableOfValues1, {"",
    Partition[Table[SortedLat[[m]][[1]], {m, 1, 74}], 1]}}]

B1,B2 are just lists of 74 numbers.
I realize the problem with the code is probably that
Partition[Table[SortedLat[[m]][[1]],{m,1,74}],1]}}]

gives me a list of 74 strings instead of 74 separate strings. Therefore it gives the error that the dimensions don't match. Is there a way to break up the list of 74 strings into 74 separate strings to make the table/grid work?
Thanks.

A: You can write
TableOfValues2 = Join[Prepend[SortedLat[[All, {1}]], {""}], TableOfValues1, 2]


text:
Q: Angularjs ng-repeat error Using Angularjs I can't do ng-repeat. First ng-repeat is working fine next is not working fine
Html code

{{fullname}}

{{strike}}

{{wickets}}

Js code

JSON response link
https://jsfiddle.net/rijo/aapfa0sL/
Kindly anyone help how to print this value using angularjs ... Thanks for all

A: Because you have some duplicate data
Use track by $index for team1_strike and team1_wickets
Try this,

        {{fullname}}

        {{strike}}

        {{wickets}}

DEMO


text:
Q: Is it possible to "link" two cells in Excel via some sort of formula? For example, I want the contents of A1 and B1 to always add up to 1000. If the user types "200" into cell A1, I want B1 to automatically update to be "800". Likewise, if the user types "600" into cell B1, I want A1 to automatically update to be "400".
I can do one or the other pretty easily—I can set A1 to be "=1000 - B1" for example, and get the second half of the behavior I want. But if the user types "200" into A1, it overwrites my formula and now I'm left with numbers that don't match and don't auto-update.
Is what I'm after possible? Or is Excel the wrong tool here?

A: You need a workaround.
Have 2 cells to have user entered values;
And then use another 2 cells to display values, So that way, you can use
if(isblank($A$1),'',2000-$A$1)
if(isblank($B$1),'',2000-$B$1)

in the other cells.


text:
Q: transform into 1D arraylist from 2D arraylist in javascript Hey guys this is reverted thing from my previous question. Not solved yet. but making the simple requirement that i need a code that will do convert my 2D array into 1D array with an condition. i.e.
A[0,2,3,7,0,0,5,3][0,2,2,4,0,0,3,0]

and i want this as result
B[2,2,4,3,0]

This does mean i want those values which are not zero from 2D array's second colum.
"Please note that the numbers are the length of particular array."

A: var checkBox = [Array1, Array2, Array3, Array4, Array5, Array6];
var dataOfUS = [A1, A2, A3, A4, A5, A6];

for (i = 0, j = 0, k = 0; i < checkBox.length, j < dataOfUS.length; i++) {
if (checkBox[i].length > 0) {
                    arrays[k] = dataOfUS[j];
                    k++;
                }
                j++;
            }

Try this might work surely, i hope......


text:
Q: Building shared libraries for Ada I'm having some trouble building shared libraries from Ada packages without using GPR's.
I have a package, Numerics, in files "numerics.ads" and "numerics.adb". They have no dependencies. There is a small build script which does:
gnatmake -Os numerics.ad[bs] -cargs -fPIC
gcc -shared numerics.o -o libnumerics.so -Wl,-soname,libnumerics.so

The .so and .ali files are installed at /usr/lib, and the .ads file is installed at /usr/include.
gnatls -v outputs the following relevant parts:
Source Search Path:
    <Current_Directory>
    /usr/include
    /usr/lib/gcc/x86_64-unknown-linux-gnu/5.1.0/adainclude

Object Search Path:
    <Current_Directory>
    /usr/lib
    /usr/lib/gcc/x86_64-unknown-linux-gnu/5.1.0/adalib

So GNAT should have no problem finding the files.
Then, trying to compile a package that depends on Numerics:
gnatmake -O2 mathematics.ad[bs] -cargs -fPIC

outputs:
gcc -c -fPIC mathematics.adb
gcc -c -I./ -fPIC -I- /usr/include/numerics.ads
cannot generate code for file numerics.ads (package spec)
gnatmake: "/usr/include/numerics.ads" compilation error

This error has me thinking GNAT doesn't recognize the shared library, and is trying to rebuild Numerics.
I'd like to be building shared libraries, and only supply the spec for reference/documentation purposes.
edit:
So, it looks like gprbuild does two things I'm not doing. The first, is also passing -lnumerics to the compiler. The second, which shouldn't matter since libnumerics.so is in a standard directory anyways, is -L«ProjectDirectory». GPRbuild is obviously not doing desired behavior either, even though it's building the dependent project. It should be using the installed library /usr/lib/libnumerics.so, but instead is using «path»/Numerics/build/libnumerics.so. Furthermore, after building Numerics with GPRbuild, and then renaming the body to make it as if the body didn't exist (like with the installed files), when building Mathematics with GPRbuild, it complains about the exact same problem. It's as if the libraries aren't even shared, and GPRBuild is just making them look that way (except readelf reports the correct dependencies inside the libraries).
Adding -lnumerics to the build script accomplishes nothing; the build error is exactly the same. I'm completely lost at this point.
edit:
Following the link from Simon, the buildscript has changed to:
gnatmake -O2 mathematics.ad[bs] \
    -aI/usr/include \
    -aO/usr/lib \
    -cargs -fPIC \
    -largs -lnumerics

The error is essentially the same:
 gcc -c -O2 -I/usr/include/ -fPIC mathematics.adb
 gcc -c -I./ -O2 -I/usr/include/ -fPIC -I- /usr/include/numerics.ads
 cannot generate code for file numerics.ads (package spec)
 gnatmake: "/usr/include/numerics.ads" compilation error

I thought to check libnumerics.so is actually a correct shared library. ldd reports:
 linux-vdso.so.1 (0x00007ffd944c1000)
 libc.so.6 => /usr/lib/libc.so.6 (0x00007f50d3927000)
 /usr/lib64/ld-linux-x86-64.so.2 (0x00007f50d3ed4000)

So I'm thinking yes, the library is fine, and gnatmake still isn't recognizing it.

A: In general, you need to install the body of the packages as well (numerics.adb in your case). Also, I suspect you want to set the ALI files
(numerics.ali) as read-only, so that gnatmake does not try to recompile them.


text:
Q: Code that works out whether the word is in ascending order or not I am new to Java I have created some code that is supposed to work out whether a word that is entered is in ascending order or not. I haven't done anything with booleans so far so I'm not entirely sure how to do this. Currently, it says that the word is in ascending order no matter if that is true or false.
class Main
{
public static void main( String args[] )
{
    System.out.print( "#Please enter a word : " );
    String word = BIO.getString();

    while(!word.equals("END")){

        Boolean inorder = true;

        while (inorder)
        {

            for (int x = 0; x < word.length(); x = x + 1)
            {
                if (word.charAt (x) >= x)
                {
                    inorder = true;
                }
                else if (word.charAt (x) < x)
                {
                    inorder = false;
                }

            }

            if (inorder=true)
            {
                System.out.print(word + "letters in ascending order" + "\n");
            }
            else if (inorder=false)
            {
                System.out.print(word + "letters not in ascending order" + "\n");
            }

            System.out.print("#Please enter a word : ");
            word = BIO.getString();

        }
    }
}
}

Thanks

A: You can simplify this considerably - just iterate over the characters in the word, comparing each one to the previous one, and return false immediately once you discover it isn't:
private static boolean isInOrder (String word) {
    char curr;
    char prev = word.charAt(0);
    for (int i = 1; i < word.length(); ++i) {
        curr = word.charAt(i);
        if (curr < prev) {
            return false;
        }
        prev = curr;
    }
    return true;
}

A: If you look closely at this line:
if (word.charAt (x) >= x)

What you're doing is comparing your number to x.
For example, say we have the word 'apple', a = 97. What you've done is check if 97 > 0, which is true.
char in Java are Unicode characters, therefore when using one as an int, they come out as their Unicode value.
In your code, basically, every word will return that it is larger because of this. Read up on the Primitive types here

A: You could need to compare word.charAt(x) with the previous character. Not the position itself.
Boolean inOrder = true;

while (inOrder ) {
    word = word.toLowerCase();
    char previous = word.charAt(0);
    for (int x = 0; x < word.length() && inOrder ; x++) {
        inOrder = word.charAt(x) >= previous;
        previous = word.charAt(x);
    }

    if (inOrder ) {
        System.out.print(word + "letters in ascending order" + "\n");
    } else if (!inOrder ) {
        System.out.print(word + "letters not in ascending order" + "\n");
    }

    System.out.print("#Please enter a word : ");
    word = BIO.getString();
}


text:
Q: Quality standards in Error reporting? It seems not good for me, reporting errors like 'General Error: '+....,
Is there any quality standard in error reporting for developers to follow?

A: Check:

*

*Exception Handling Best Practices
in .NET

*User Friendly Exception Handling
Strategies

*Microsoft Application Blocks for
.NET - Exception Management
Application Block Overview

*User Friendly Exception
Handling

A: *

*https://bugzilla.mozilla.org/page.cgi?id=bug-writing.html

*http://www.chiark.greenend.org.uk/~sgtatham/bugs.html

*http://testobsessed.com/wordpress/wp-content/uploads/2007/01/webr.pdf


text:
Q: pg_query like with timestamp I get 0 results if I query the timestamp column for entries that contain 2017 (or any other year).
The data in w_presse_erscheinung is a "timestamp without timezone"
and looks like this for example: 2017-06-01 00:00:00
I assume there is something wrong with the LIKE part of the query ...
My query looks like this:
        $result = pg_query("
        SELECT
        name,
        w_presse_link,
        w_presse_erscheinung,
        w_presse_quelle,
        description

        FROM adempiere.w_presse
        WHERE isactive ='Y'
        AND description='PS' AND w_presse_erscheinung LIKE '%2017%'
        ORDER BY w_presse_erscheinung
        DESC
        ")

A: Instead of relying on string conversions, you could explicitly extract the year from the timestamp:
EXTRACT(YEAR FROM w_presse_erscheinung) = 2017

A: You cannot use like with a timestamp field like that. Either typecast the timestamp field to varchar then use like or use extract function to match the year from the field.


text:
Q: JOIN using LINQ LAMBDA I am trying to get a list of customers with their addresses. In my database, Customer1 has 1 address and Customer2 has 2 addresses.
I am joining Customer with Address, like this:
var customers = _dbContext.Customer.Join(_dbContext.Address, c => c.Id, a => a.EntityId, (c, a) => new { Customer = c, Address = a });

I would like the result to be 2 Customers with addresses nested inside each. Instead, I get 3 records (a record for each address), as shown below. Does anyone know how I can adjust my query to get the result I am looking for? Thanks!
[{"customer":{"id":1,"companyName":"Customer2","firstName":"Donald","lastName":"Trump"},"address":{"id":5,"entityId":1,"city":"Atlanta","state":"GA","zip":"33333"}},

{"customer":{"id":1,"companyName":"Customer2","firstName":"Bill","lastName":"Clinton"},"address":{"id":7,"entityId":1,"city":"Gainesville","state":"FL","zip":"33333"}},

{"customer":{"id":2,"companyName":"Customer1","firstName":"Tom","lastName":"Hanks"},"address":{"id":9,"entityId":2,"city":"Miami","state":"FL","zip":"33333"}}]

A: Try code below
var customers = _dbContext.Customer
    .GroupJoin(
        _dbContext.Address,
        c => c.Id,
        a => a.EntityId,
        (c, a) => new
        {
            c.Id,
            c.CompanyName,
            c.FirstName,
            c.LastName,
            Address = a.ToList()
        }
    );

Or using query style
var customers = from c in _dbContext.Customer
    join a in _dbContext.Address on c.Id equals a.EntityId into g
    select new
    {
        c.Id,
        c.CompanyName,
        c.FirstName,
        c.LastName,
        Address = g.ToList()
    };

A: This will solve your problem. You need to Group customers and loop for addresses of each customer.
var customers = _dbContext.Customer
                    .Join(_dbContext.Address
                    , c => c.Id
                    , a => a.EntityId, (c, a) => new {  c.Id, Address = a }).GroupBy(j => j.Id);

                foreach (var customer in customers)
                {
                    Console.WriteLine($"Customer :{customer.Key} , Address : { customer.Count() }");
                    foreach (var Addr in customer)
                    {
                        Console.WriteLine(Addr.xxxx);
                    }
                }


text:
Q: Flutter image cache for current session only I've built a music player app which automatically fetches songs from a server at start-up.
The issue is that, if I use NetworkImage to display the covers for the songs on an overview page, they are refetched everytime I leave the page and then return to it.
I already tried using CachedNetworkImage, but I don't want to store the song covers in the users cache. The images should persist for one session and then be disposed.
I could probably clear the cache everytime the user closes the app but there has to be a better way

A: You could try storing the images in memory while app is running, then dispose when app is closed.
Third party libraries such as flutter_cache_manager can help achieve this.
It allows persistence of images for app session's duration.


text:
Q: How to print all tf.Tensors of a model in a loop? I have the list of all tensors in my model which had the float32 type:
import os
import os.path
import tensorflow as tf
from tensorflow.python.platform import gfile
import numpy
numpy.set_printoptions(threshold=numpy.nan)

with tf.Session() as sess:
    model_filename = 'MY_pb_file.pb'
    with gfile.FastGFile(model_filename, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _= tf.import_graph_def(graph_def,name='')
from pprint import pprint
    pprint([out for op in tf.get_default_graph().get_operations() if op.type != 'Placeholder' for out in op.values() if out.dtype == tf.float32])

which gives me all the list:
<tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/add:0' shape=(16,) dtype=float32>, <tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/Rsqrt:0' shape=(16,) dtype=float32>,
 <tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/mul:0' shape=(16,) dtype=float32>,
 <tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/mul_1:0' shape=(?, 64, 64, 16) dtype=float32>,
 <tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/mul_2:0' shape=(16,) dtype=float32>,
 <tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/sub:0' shape=(16,) dtype=float32>, <tf.Tensor 'MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/add_1:0' shape=(?, 64, 64, 16) dtype=float32>,
...

At this point I can use sess.run('NAME') to see its value:
>>> sess.run('MobilenetV1/MobilenetV1/Conv2d_1_pointwise/BatchNorm/batchnorm/mul:0')
array([  0.51656026,  29.6620369 ,   0.48722425,   7.73186255,
        -9.51173401,   0.60846734,   0.21111809,   0.23865609,
        23.85105324,   1.04134226,  28.59620476,  35.79195023,
         0.34110394,   0.5557093 ,  10.39805031,  10.99952412], dtype=float32)

However, I would like print all tf.Tensor values in a loop. How can I do that?
Apparently, some needs a dictionary to be defined:
sess.run('MobilenetV1/MobilenetV1/Conv2d_1_pointwise/Relu6:0')

For example:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input' with dtype float and shape [?,128,128,3]
     [[Node: input = Placeholder[dtype=DT_FLOAT, shape=[?,128,128,3], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

A: When you request the value of a tensor, Tensorflow computes that value in the graph as tensor values are not usually retained across different calls to sess.run (that's what variables are for). It seems like the operations necessary to compute the value of the tensor you requested need input from one of your input placeholders (named input in the error statement), thus you must feed a value for that placeholder through the feed dictionary in sess.run.
Following your comment, consider this example:
import tensorflow as tf

a = tf.constant(4)
b = tf.constant(3)
c = tf.placeholder(tf.int32, [], 'c')

d = a + b
e = a + c

Requesting tensor d works fine:
with tf.Session() as sess:
    print(sess.run(d))  # prints 7

However, requesting e throws the same error you report:
with tf.Session() as sess:
    print(sess.run(e))

which prints
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'c' with dtype int32
     [[Node: c = Placeholder[dtype=DT_INT32, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

This happens because in order to evaluate e we must compute a + c and if we don't feed a value to c, this is not possible. So, e.g., this works:
with tf.Session() as sess:
    print(sess.run(e, feed_dict={c: 1}))  # prints 5

Evaluating d worked fine because the computation path necessary to evaluate d does not involve a placeholder. So, to fix your problem, you should feed a value for the placeholder called 'input' in your call to sess.run('MobilenetV1/MobilenetV1/Conv2d_1_pointwise/Relu6:0').


text:
Q: Grails inheritance concern When a domain class inherits from a parent domain class in Grails, do static mappings and static constraints also get inherited or must they be restated in children classes?
Does inheritance only work in domain classes or can controllers and services inherit also?

A: Controllers and Services can be inherited as well as domain classes. for controllers see the official example of RestfulController Superclass in the doc. To do inheritance on domain classes, there are some thigs, that have to be recognized like the inheritance of the mapping closure. For more information see here. For Services, it could also be reasonable to use mixins as an alternative (see here).


text:
Q: SyntaxError when trying to do anything in npm I came back to a Win10 PC I haven't used in a while. First thing, I tried to update npm with
> npm i npm -g

I got back this:
added 290 packages, removed 250 packages and updated 37 packages in 38.815s
   ╭─────────────────────────────────────╮
   │                                     │
   │   Update available 5.0.0 → 6.4.1    │
   │     Run npm i -g npm to update      │
   │                                     │
   ╰─────────────────────────────────────╯

Then, I tried to run npm i -g npm and got:
     let notifier = require('update-notifier')({pkg})
      ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:974:3

Now when I try to do anything, I get that same error. In case you were wondering I was trying to update from npm 5.0.0 to 6.4.1.

Things I've tried
I Googled this error and found the following:

*

*Update Node

*

*Following these instructions I first tried to clear npm's cache with npm cache clean -f, but got the same SyntaxError.

*The same instructions also say to do some stuff with nvm, which I don't have, so I tried to install it with npm i nvm -g, but same error.

*use strict, even though I know this is for a program using node. I wanted to be sure I tried everything before posting a question.

*

*'"use strict"' is not recognized as an internal or external command,
operable program or batch file.

*Fresh npm install of webpack.js is throwing Block-scope error but this didn't seem to apply to me because I'm not using Visual Studio, and I haven't done anything with babel or webpack or es6. I'm just trying to update npm.

A: I couldn't find any answers so I decided to completely uninstall node and npm using these instructions: https://stackoverflow.com/a/20711410/1152809
Then I reinstalled node and everything works as expected.


text:
Q: Why I do not get push notifications from Firebase in Swift? I set this code in my AppDelegate:
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.Alert, .Badge, .Sound]
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(authOptions, completionHandler: { (granted: Bool, error: NSError?) in
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.currentNotificationCenter().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self
        })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil))
}

Also this parts:
internal func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    print(userInfo)
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                   fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)
}

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    //Handle the notification
}

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
    //Handle the notification
}

I also uploaded development APNs into the Apple Developers. In the Firebase console it writes that notification was successfully sent, but I do not get any push notification. Can anyone please help me to detect where my mistake is?
I have worked on it for 3 days. Searched a lot, but nothing.

A: *

*Add FIRApp.configure() to the didFinishLaunchingWithOptions:

*Add FIRMessaging.messaging().connect { (error) in
        if error != nil {
            print("Unable to connect with FCM. \(error)")
        } else {
            print("Connected to FCM.")
        } to the end of didFinishLaunchingWithOptions:

*Implement the FIRMessageDelegate function
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {

    print(remoteMessage.appData)
}

*Add FIRMessaging.messaging().appDidReceiveMessage(userInfo) to func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
The finishing code should look like this:
import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FIRApp.configure()

    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    FIRMessaging.messaging().connect { (error) in
        if error != nil {
            print("Unable to connect with FCM. \(error)")
        } else {
            print("Connected to FCM.")
        }
    }
    application.registerForRemoteNotifications()

    return true
}

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {

    print("applicationReceivedRemoteMessage ")
    print(remoteMessage.appData)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)

    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

A: For anyone still looking, check the last answer here: ios10, Swift 3 and Firebase Push Notifications (FCM)

*

*Check your push notification entitlement and switch it on. Target > Capabilities > Push notifications.


text:
Q: Put each element of a vector as a column in each dataframe contained in a list I have a list with dataframes that have the same number of columns and different number of rows. Like this example:
dfs_list <-  list(data.frame(var1 = seq(1:10), var2 = LETTERS[1:10]),
                  data.frame(var1 = seq(1:20), var3 = LETTERS[1:20]),
                  data.frame(var1 = seq(1:15), var2 = LETTERS[1:15]))

To each of the data frames I need to add a column at the beginning according to a vector that I have with the cities
city <- c("city1", "city2", "city3")

Always the number of dataframes in dfs_list matches the number of elements of the vector city
I made this solution with a for loop
for (i in seq_along(city)) {
  dfs_list[[i]] <- mutate(dfs_list[[i]], city = city[i], .before = 1)
}

I would like to know if there is another solution without the need to use the for loop, since I am finding it a bit slow when I generalize it for a large group of cities.

A: We may use Map with cbind in base R
dfs_list <- Map(cbind, city = city, dfs_list)

-output
dfs_list
$city1
    city var1 var2
1  city1    1    A
2  city1    2    B
3  city1    3    C
4  city1    4    D
5  city1    5    E
6  city1    6    F
7  city1    7    G
8  city1    8    H
9  city1    9    I
10 city1   10    J

$city2
    city var1 var3
1  city2    1    A
2  city2    2    B
3  city2    3    C
4  city2    4    D
5  city2    5    E
6  city2    6    F
7  city2    7    G
8  city2    8    H
9  city2    9    I
10 city2   10    J
11 city2   11    K
12 city2   12    L
13 city2   13    M
14 city2   14    N
15 city2   15    O
16 city2   16    P
17 city2   17    Q
18 city2   18    R
19 city2   19    S
20 city2   20    T

$city3
    city var1 var2
1  city3    1    A
2  city3    2    B
3  city3    3    C
4  city3    4    D
5  city3    5    E
6  city3    6    F
7  city3    7    G
8  city3    8    H
9  city3    9    I
10 city3   10    J
11 city3   11    K
12 city3   12    L
13 city3   13    M
14 city3   14    N
15 city3   15    O

Or in tidyverse, this can be done with map2 (or if it is a named list, then imap)
library(purrr)
library(dplyr)
map2(dfs_list, city, ~ .x %>%
      mutate(city = .y, .before = 1))


text:
Q: Parsing XML in Go after accessing it through io/ioutil net/http Any idea why this parsing is not working when accessing the XML directly from the site and it works when I copy and paste it into a var?
package main

import (
  "encoding/xml"
  "fmt"
  "strings"
  "io/ioutil"
  "net/http"
)

type Sitemapindex struct {
  Locations []Location `xml:"channel>item"`
}

type Location struct {
  Loc string `xml:"title"`
}

func (e Location) String () string {
  return fmt.Sprintf(e.Loc)
}

func main() {
  resp, _ := http.Get("https://www.sec.gov/Archives/edgar/xbrlrss.all.xml")
  bytes, _ := ioutil.ReadAll(resp.Body)
  string_body := string(bytes)
  var s Sitemapindex
  decoder := xml.NewDecoder(strings.NewReader(string_body))
  decoder.Strict = false
  decoder.Decode(&s)
  fmt.Println(s)
}

A: The content you're parsing is encoded as windows-1252. To properly decode this data, the XML decoder needs to be parameterized by a charset reader that can read the specified charset.
import (
    "encoding/xml"
    "golang.org/x/net/html/charset"
)

decoder := xml.NewDecoder(reader)
decoder.CharsetReader = charset.NewReaderLabel
err := decoder.Decode(&s)

I guess that the error returned at your attempt to decode the data tells something similar.


text:
Q: {searchTerms} Path:{Site.URL} not returning any results I have the same unanswered issue as in :
Using a Search Result Source to limit to current site
According to Microsoft's documentation at http://technet.microsoft.com/en-us/library/jj683123(v=office.15).aspx, the {Site.URL} variable returns the "URL of the site from where the query was issued." Unfortunately, that is not what seems to be happening.
So, If this query: {searchTerms}{Site.URL} doesn't work, something else must be wrong ?!

A: The query should be {searchTerms} Path:{Site.URL}, but this will still only reference the content in the site with the WebPart.
When Microsoft is use the description

URL of the site from where the query was issued.

then it's due to them expecting you to configure a WebPart file and reuse that in many sites which without the token would require you the edit the WebPart after inserting it.
One solution (not tested) might be do change the initial search page to not contain the search WebPart, but instead some javascript which takes the original Url in document.referrer, remove page name and /Pages and passed that in a QueryString like OrigSite to the new Real search page along with the original k query string. Then you can use {searchTerms} Path:{QueryString.OrigSite}


text:
Q: Regexp in Perl/TCL I am having a string and want to get some part of it. Suppose I am having a string say "set aid ODU4-4-3". I want to take only ODU from it. Whereas the pattern of string is not fixed. IT may some like ODU,ODU4,ODUX. I am not getting how to fetch this
$aid = "ODU4-9-1";
$aid =~ /(\w)+\d*-\d-\d/;
print " value is $1"

Output
value is ODU4

I need the value to be ODU only whereas the string pattern may  change. It may be ODU-4-3 only or can go ODU4-4-3.

A: and the Tcl:
if {[regexp {^[[:alpha:]]+} $string letters]} {
    puts $letters
}

A: Version of @M42 's answer that returns all matches:
my @allmatches = $aid =~ /([A-Z]{3}).*?\-\d\-\d/;

A: How about:
$aid =~ /([A-Z]{3}).*?-\d-\d/;

for any length more than 0 and case insensitive, use
$aid =~ /([a-zA-Z]+).*?-\d-\d/;

A: If you want only alphabets in odu then this should do the trick
$aid =~ /([[:alpha:]]+)/;